在ViewModel中,我们可以为Encapsulation
应用MutableLiveData
,如Android architecture所示:
private val _dataLoading = MutableLiveData<Boolean>()
val dataLoading: LiveData<Boolean>
get() = _dataLoading
因此,dataLoading
不能从片段或活动中更改,因为它是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}">
那么,我们如何将Encapsulation
应用于Google样本中的ObservableBoolean
?
你可以有
private val loading = ObservableBoolean(false)
在你的vm
fun isLoading() = loading
如果要从片段/活动中更改加载状态,则可以公开setter
fun setLoading(value: Boolean) {
loading.set(value)
}