More GameViewModel Functions: roll() and pass()

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)
  )
  }
  }
 }
 
 fun​ ​pass​() {
 val​ currentPlayer = players.firstOrNull { it.isRolling }
 if​ (currentPlayer != ​null​ && canPass.value == ​true​) {
  updateFromGameHandler(GameHandler.pass(players, currentPlayer))
  }
 }

By now, a lot of this syntax should look familiar. But the use of .value may look odd. With slots.value, we’re using a null-safe call to let since we’re getting the (nullable) value out of a LiveData object. This is the reason for the slightly strange conditional statements in each function, too. We can’t just use canRoll.value and canPass.value on their own since they’re technically not Boolean objects but rather Boolean? objects. Luckily, instead of having to do a null check then check the Boolean value, we can compare against true. By doing this, a value of false or null will both fail and we skip going to the GameHandler. It’s a handy shortcut that gets us the exact functionality we want.

With both actions in place, we can get to the core piece of GameViewModel: the updateFromGameHandler function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.13.194