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?
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()
viewModel-ktx
library in Android Jetpack.