Chapter 12. Live Data: Leaping into Action

image

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:

image

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.