From the course: Android Compose with Kotlin

Unlock this course with a free trial

Join today to access over 24,800 courses taught by industry experts.

Observe data in a ViewModel

Observe data in a ViewModel - Kotlin Tutorial

From the course: Android Compose with Kotlin

Observe data in a ViewModel

- [Person] The "remember" function retains state across re-compositions, not activity or process recreation. When the phone is rotated, a configuration change takes place which destroys and recreates your activity, thus losing any previous state. This is where view models and StateFlows can help us. StateFlow is an observable data-holder class. It requires an initial value to be passed in the constructor and allows UI components to observe data changes automatically. At this point, it likely feels like there's state everywhere. When I first started working with Compose, at least that's how I felt. Here's how I keep the states clear in my head. There are two types, Compose State and Kotlin StateFlow. The Compose State uses "State<T>" and "MutableState<T>." It's observed by Compose to trigger UI re-composition when changed, and it automatically is lifecycle-aware within Compose, whereas with the Kotlin StateFlow that uses "StateFlow<T>" and "MutableStateFlow<T>." It's an asynchronous…

Contents