Sharing data between Views and composable functions
State is app data that may change over time. Recomposition occurs when state being used by a composable changes. To achieve something similar in the traditional View world, we need to store data in a way that changes to it can be observed. There are many implementations of the Observable pattern. The Android Architecture Components (and subsequent Jetpack versions) include LiveData
and MutableLiveData
. Both have been used frequently inside ViewModels to store state outside activities, but are increasingly often replaced by other techniques, such as StateFlow
and MutableStateFlow
.
Revisiting ViewModels
I introduced you to ViewModels in the Surviving configuration changes section of Chapter 5, Managing State of Your Composable Functions, and the Persisting and retrieving state section of Chapter 7, Exploring App Architecture. Before we look at how to use ViewModels to synchronize data between Views and composable functions, let...