collectAsStateWithLifecycle
Collect flows safely with the lifecycle.
Collecting Flows Safely
When a Composable collects a flow, it should ideally stop collecting while the screen is in the background and resume when it returns.
The tool for this is collectAsStateWithLifecycle().
The Problem with collectAsState
Plain collectAsState() keeps collecting as long as the Composable is in the composition — even when the app is in the background.
This can waste resources and process updates the user cannot see.
All lessons in this course
- Why Use a ViewModel?
- Exposing State from ViewModel
- The Android Lifecycle
- collectAsStateWithLifecycle