androidkotlinandroid-jetpack-composeandroid-viewmodel

Jetpack Compose: 'by viewModels()' vs 'viewModel<ViewModelName>()'


What's the difference here?

val myViewModel: MyViewModel by viewModels()

versus

val myViewModel = viewModel<MyViewModel>()

How does the first way work? How does it know which ViewModel to initialize? From the type-annotation after the variable-name?


Solution

  • In Android development using Kotlin, there are two common ways to initialize ViewModels in ViewModel-backed fragments or activities: by viewModels() and viewModel() functions provided by Android Jetpack libraries.

    by viewModels()

    viewModel()