我们可以使用以下命令初始化ViewModel

private val viewModel: CharactersViewModel by viewModels()

viewModel = ViewModelProvider(this).get(CharactersViewModel::class.java)

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 unf或tunately failed to understand it. Can anyone help me understand this?

推荐答案

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实例)

因此,使用视图模型等对象的延迟初始化可以减少片段的启动影响,从而更快地加载和显示其内容,而不是直接初始化它们.

Kotlin相关问答推荐

如何在Jetpack Compose中从领域查询中读取数据?

如何使用multiset与JOOQ获取关联的记录列表?

为什么 Kotlin 在将协变类型参数转换为不变类型参数时会产生 Unchecked Cast 警告?

使用 Jetpack Compose 使用参数导航

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

从带有 Room 和 Flows 的 SQLite 表中获取祖先树

T except one class

如何使 TextInputEditText 只读?

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

如何通过反射使用 Kotlin 对象

无法为 retrofit2.Call 调用无参数构造函数

main函数和常规函数有什么区别?

将ExpectedException与Kotlin一起使用

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

在Kotlin中使用@Service时引发异常

如何从协程范围返回值

Kotlin - 具有私有构造函数的类的工厂函数

Kotlin 错误:public function exposes its 'public/*package*/' return type argument

Android room DAO 接口不适用于继承

Kotlin Realm:如果类包含自定义构造函数,则必须声明一个不带参数的公共构造函数