使用“by viewModels()"初始化视图模型vs “ViewModelProvider(this).get(ViewModel::class.java)"在安卓中 [英] View model initialization using "by viewModels()" vs "ViewModelProvider(this).get(ViewModel::class.java)" in android
问题描述
我们可以使用
private val viewModel: CharactersViewModel by viewModels()
或
viewModel = ViewModelProvider(this).get(CharactersViewModel::class.java)
Herer CharactersViewModel 是我们的 ViewModel 类.我的问题是什么时候使用哪个?两者都包含相同的目的吗?我已经阅读了 ViewModel 的 android 官方文档.文档说 by viewModels()
Kotlin 属性委托.但可惜没能看懂.谁能帮我理解一下?
Herer CharactersViewModel is our ViewModel class. My question is when to use which?
Do both contain the same purpose? I have read the android official documentation of ViewModel.The documentation says by viewModels()
Kotlin property delegate. But unfortunately failed to understand it. Can anyone help me understand this?
推荐答案
两者都做同样的事情,但第一个有区别优势.Kotlin 属性委托使用了Lazy Initialization
的思想.在维基百科上,您可以找到它的简要定义:
Both of them do the same thing, but there is a discriminative advantage for the first one. Kotlin property delegation uses the idea of Lazy Initialization
. On Wikipedia you can find a brief definition for it:
在计算机编程中,延迟初始化是一种将对象的创建、值的计算或其他一些昂贵的过程延迟到第一次需要它的策略.它是一种惰性求值,特指对象或其他资源的实例化.
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.
因此,当您使用您提到的第一种方法时,您就利用了惰性属性.这意味着只有在第一次访问时才会创建 ViewModel 实例.
Therefore, when you use the first approach you mentioned, you take the advantage of lazy properties. It means that the ViewModel instance becomes created only upon first access.
以下面的代码为例:
class YourFragment : Fragment() {
private val viewModel: CharactersViewModel by viewModels()
// other codes ...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// doing some view initialization ...
viewModel.someLiveData.observe(viewLifecycleOwner) {
// ...
}
}
}
如果 viewModel.someLiveData.observe(viewLifecycleOwner)
是第一次触摸 viewModel
字段,它的实例化将在那里发生.(创建一个 CharactersViewModel
实例)
If viewModel.someLiveData.observe(viewLifecycleOwner)
is the first time that the viewModel
field is touched, the instantiation of it will happen there. (creation of a CharactersViewModel
instance)
因此,使用像视图模型这样的对象的延迟初始化可以减少片段的启动影响,这会导致加载和显示其内容的速度更快,而不是直接初始化它们.
So, using lazy initialization of objects like the view model reduces the start-up impact of your fragment which leads to faster loading and showing its content as opposed to direct initialization of them.
这篇关于使用“by viewModels()"初始化视图模型vs “ViewModelProvider(this).get(ViewModel::class.java)"在安卓中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!