More GameViewModel Functions: roll() and pass()

Kotlin and Android Development featuring Jetpack — by Michael Fazio (33 / 125)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Start a Game | TOC | Update the UI 👉

I’ve pushed it off long enough; let’s finally look at what’s happening with all those TurnResult objects we’ve been creating. We’re adding or updating three functions in the GameViewModel: roll, pass, and updateFromGameHandler(result: TurnResult). The latter method will be called in the first two functions to set our LiveData values accordingly.

We’ll get to the updateFromGameHandler piece in a minute, but first I want to address the roll and pass functions, as both have similar implementations to each other. Both functions will get the current player (the first with isRolling as true), make sure the resulting Player? object is not null, check if the requested move is valid, then call the GameHandler. The response from the GameHandler function will then be sent into the updateFromGameHandler function. In addition, the roll function will get the game’s current slots and send those along to the GameHandler. The code for both functions looks like this:

​ ​fun​ ​roll​() {
​ slots.value?.let { currentSlots ->
​ ​// Comparing against true saves us a null check​
​ ​val​ currentPlayer = players.firstOrNull { it.isRolling }
​ ​if​ (currentPlayer != ​null​ && canRoll.value == ​true​) {
​ updateFromGameHandler(
​ GameHandler.roll(players, currentPlayer, currentSlots)…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.