ViewModel类中ObservableBoolean的封装

时间:2019-04-12 10:50:10

标签: android encapsulation android-viewmodel

在ViewModel中,我们可以将Encapsulation应用于MutableLiveData,如Android architecture所示:

private val _dataLoading = MutableLiveData<Boolean>()
    val dataLoading: LiveData<Boolean>
        get() = _dataLoading

结果dataLoading不能从Fragment或Activity更改,因为它是LiveData而不是MutableLiveData

例如,我们可以在ViewModel类中将ObservableBoolean用于DataBinding的情况:

val isLoading = ObservableBoolean(false)

由于我们在DataBinding中使用它,因此它不能是私有的:

<data>
        <variable
                name="vm"
                type="com.sample.android.ui.DetailViewModel"/>
    </data>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:visibleGone="@{!vm.isLoading}">

那么,如何如Google示例所示将Encapsulation应用于ObservableBoolean

1 个答案:

答案 0 :(得分:0)

您可以拥有

private val loading = ObservableBoolean(false)

并在您的vm

fun isLoading() = loading

如果您想从片段/活动中更改加载状态,可以公开一个setter

   fun setLoading(value: Boolean) {
       loading.set(value)
   }