问题
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.
回答1:
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)
}
来源:https://stackoverflow.com/questions/58106707/how-does-kotlin-use-this-by-delegate-to-instantiate-the-viewmodel