Persisting and retrieving state
State is app data that may change over time. In a Compose app, state is typically represented as instances of State
or MutableState
. If such objects are used inside composable functions, a recomposition is triggered upon state changes. If a state is passed to several composables, all of them may be recomposed. This leads to the state hoisting principle: state is passed to composable functions rather than being remembered inside them. Often, such state is remembered in the composable that is the parent of the ones using the state. An alternative approach is to implement an architectural pattern called ViewModel
. It is used in many user interface (UI) frameworks on various platforms. On Android, it has been available since 2017 as part of the Android Architecture Components.
The general idea of a ViewModel
is to combine data and access logic that is specific to a certain part of an app. Depending on the platform, this may be a screen, a window, a dialog...