I was reading through the google android architecture example and came across this.Can someone explain to me how this delegate works?
private val viewModel by viewModels<TasksViewModel> { getViewModelFactory() }
where getViewModelFactory is an extension method that returns a ViewModelFactory and TasksViewModel is an instance of ViewModel()
The way that I read this is similar to:
private val viewModel: TasksViewModel by Fragment.ViewModel(ViewModelFactory)
can someone elaborate on if my understanding is correct.
Kotlin Vocabulary: Delegates Delegation is a design pattern in which an object handles a request by delegating to a helper object, called the delegate. The delegate is responsible for handling the request on behalf of the original object and making the results available to the original object.
What is the correct way to access the shared view model using the Kotin property delegate approach? Enter one or more words to complete the sentence. Use a LiveData to return a different LiveData instance based on the value of another instance.
Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object.
by viewModels(...)
is part of fragment-ktx
library, it's a convienience short hand for creating a lazy
delegate obtaining ViewModels
.
// creates lazy delegate for obtaining zero-argument MyViewModel
private val viewModel : MyViewModel by viewModels()
// it's functionally equal to:
private val viewModel by lazy {
ViewModelProvider(this).get(MyViewModel::class.java)
}
// with factory:
private val viewModel : MyViewModel by viewModels { getViewModelFactory() }
// is equal to:
private val viewModel by lazy {
ViewModelProvider(this, getViewModelFactory()).get(MyViewModel::class.java)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With