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实例.
Given below code as an example:
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
实例)
因此,使用视图模型等对象的延迟初始化可以减少片段的启动影响,从而更快地加载和显示其内容,而不是直接初始化它们.