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 ...
Get Head First Android Development, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.