Create Another ViewModel (Game)

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Customize the Player List Items | TOC | Bind ViewModel to a Fragment (Game) 👉

This class will look similar to PickPlayersViewModel on a high level, but there’s going to be a lot more going on here since this will handle the connection between the Game view and the GameHandler we’ll be building in Chapter 4, Update LiveData with Conditional Game Logic.

We’re going to start with an empty GameViewModel class, and we can add the pieces in later on. It’ll look like this:

​ ​package​ ​dev.mfazio.pennydrop.viewmodels​

​ ​import​ ​androidx.lifecycle.ViewModel​

​ ​class​ GameViewModel: ViewModel() {
​ ​//Logic will go in here.​
​ }

Once GameViewModel is available, we can add a List<Player> to hold everyone we added in the Pick Players view. We’ll need a little setup before we can do that, though.

Add Players to the Game

To get the players into a game, we’re going to need to do a few things: we need a Player class, we need the List<Player> that I mentioned a bit ago, and finally, we need a way to get players from the Pick Players view into GameViewModel. Let’s walk through each of these steps now.

Create the Player Class

--

--

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.