Kotlin如何通过委托使用此实例化视图模型 [英] How does kotlin use this by delegate to instantiate the viewmodel

查看:45
本文介绍了Kotlin如何通过委托使用此实例化视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读google android体系结构示例,并遇到了这个问题.有人可以向我解释此委托的工作原理吗?

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() }

其中getViewModelFactory是返回ViewModelFactory的扩展方法,而TasksViewModel是ViewModel()的实例

where getViewModelFactory is an extension method that returns a ViewModelFactory and TasksViewModel is an instance of ViewModel()

我的阅读方式类似于:

private val viewModel: TasksViewModel by Fragment.ViewModel(ViewModelFactory)

有人能详细说明我的理解是否正确.

can someone elaborate on if my understanding is correct.

推荐答案

by viewModels(...) fragment-ktx 库,它是创建lazy委托以获得ViewModels的便捷捷径.

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)
}

这篇关于Kotlin如何通过委托使用此实例化视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆