Chapter 12. Live Data: Leaping into Action
Your code often needs to react to property value changes.
If a view model property changes value, for example, the fragment might need to respond by updating its views or navigating elsewhere. But how does a fragment get to hear when a property’s been updated? Here, we’ll introduce you to live data: a way of telling interested parties when something’s changed. You’ll learn all about MutableLiveData, and how to make your fragment observe properties of this type. You’ll discover how the LiveData type helps maintain your app’s integrity. Soon, you’ll be writing apps that are more responsive than ever before...
The Guessing Game app revisited
In the previous chapter, we built a Guessing Game app that lets the user guess which letters are included in a secret word. When the user guesses all the letters or runs out of lives, the game ends.
To stop the fragment code from becoming too bloated and maintain the app’s state when the user rotated the device screen, we used view models for the app’s game logic and data. GameFragment uses GameViewModel for its logic and data, and ResultViewModel holds the game result that’s needed by ResultFragment:
When each fragment is displayed, or the user makes a guess, the fragments get the latest values ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access