0PricingLogin
Jetpack Compose Academy · Lesson

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

  1. Why ViewModel Survives Rotation
  2. viewModel() in a Composable
  3. Modeling a UiState Data Class
  4. collectAsStateWithLifecycle
← Back to Jetpack Compose Academy