实施ViewModel的良好做法

时间:2018-09-24 16:03:55

标签: android kotlin android-architecture-components

有人知道实现视图模型逻辑的良好实践吗?基于事件还是基于动作?

class EventBasedVM : ViewModel() {
    fun onResume() {
        fetchInformation1()
        fetchInformation2()
    }
}

class ActionBasedVM : ViewModel() {
    fun fetchInformation1() {
    }

    fun fetchInformation2() {
    }
}

1 个答案:

答案 0 :(得分:0)

尽管您提到的两种方法都适用于特定的用例,但我还是要在列表中添加另一种方法:

 class InitialisationBasedVM : ViewModel() {

    val informationLiveData = MutableLiveData<String>()

    init {
        fetchInformation()
    }

    private fun fetchInformation() {
        // call you async code and eventually post the value to the observers
        informationLiveData.postValue("whatever")
    }
}

ViewModel构造函数中获取数据的方法可确保在配置发生更改时不会再次获取数据。您还可以公开fetchInformation()方法,并在需要重新加载数据(即拉动刷新)的某些操作上从“视图”中调用。

相关问题