Create a ViewModel (Pick Players)

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 3 Bind Data with ViewModels | TOC | Bind ViewModel to a Fragment (Pick Players) 👉

View models as a concept aren’t an exclusively Android-focused idea; plenty of other languages/frameworks/platforms have the concept of a view model in one way or another. In a general sense, a view model holds UI-related data for a given view. This way, the UI can focus on what to display while the view model handles how you get that data.

With Jetpack, ViewModel is a specific class we can use to handle UI data for view components, in our case the Fragment classes. A ViewModel may also contain LiveData, which will automatically send updates to a UI controller whenever the data changes. Since ViewModel classes are life-cycle aware, they only send LiveData over when a given Fragment (or Activity) is currently active. This avoids potential errors and unnecessary data updates, making your app faster and more stable.

We’re going to create a new ViewModel called PickPlayersViewModel, bind it to our PickPlayersFragment, and create some NewPlayer objects as LiveData for use in setting up the game. But first, as we did with the Navigation component, we need to add two dependencies before we can use the library.

Add the ViewModel and LiveData Dependencies

--

--

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.