How does kotlin use this by delegate to instantiate the viewmodel

时光总嘲笑我的痴心妄想 提交于 2020-08-19 07:03:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!