在ViewModel类中封装ObservableBoolean

问题描述 投票:0回答:1

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

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

因此,dataLoading不能从片段或活动中更改,因为它是LiveData而不是MutableLiveData

例如,我们可以在ViewModel类中用于ObservableBooleanDataBinding怎么样:

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}">

那么,我们如何将Encapsulation应用于Google样本中的ObservableBoolean

android encapsulation android-viewmodel
1个回答
0
投票

你可以有

private val loading = ObservableBoolean(false)

在你的vm

fun isLoading() = loading

如果要从片段/活动中更改加载状态,则可以公开setter

   fun setLoading(value: Boolean) {
       loading.set(value)
   }
© www.soinside.com 2019 - 2024. All rights reserved.