viewModel() in a Composable
Obtain and scope a ViewModel correctly.
Getting a ViewModel
Inside a Composable you don’t construct a ViewModel with new. Instead you call the viewModel() function to fetch the right instance.
val vm: CounterViewModel = viewModel()Where It Comes From
The viewModel() helper looks up the nearest lifecycle owner and returns the ViewModel scoped to it, creating one only if none exists yet.
All lessons in this course
- Why ViewModel Survives Rotation
- viewModel() in a Composable
- Modeling a UiState Data Class
- collectAsStateWithLifecycle