如何将 LiveData 应用于 xxxFragment.class 而不是 XML

How to apply LiveData to xxxFragment.class instead of XML

如何将实时数据 isRefreshing应用到swiperefreshLayout.isRefresh?

xxxViewModel.class中的代码:

var isRefreshing = MutableLiveData<Boolean>()

fun refresh() {
    viewModelScope.launch(Dispatchers.Main) {
        isRefreshing.value = true

        withContext(Dispatchers.IO) {
            fun doInBackground() // takes a long time
        }
   
        isRefreshing.value = false
    }
}

xxxFragment.class中的代码:

binding.swiperefreshLayout.setOnRefreshListener {
    xxxViewModel.refresh()
}

// error here, require Boolean, found MutableLiveData<Boolean>
binding.swiperefreshLayout.isRefreshing = xxxViewModel.isRefreshing 

通常我将实时数据应用到 XML,如下所示,但我在 XML.

中找不到 swiperefreshlayout.isRefreshing
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swiperefresh_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        isFreshing = "@{xxxViewModel.isRefreshing}">

您所做的是获取 liveData“isRefreshing”的当前值。 (您还需要添加 .value 以获得与 liveData 关联的基础值)

binding.swiperefreshLayout.isRefreshing = xxxViewModel.isRefreshing.value?:false

相反,您应该在初始化视图模型后观察实时数据的变化。

 xxxViewModel.apply {

    
    isRefreshing.observe(viewLifecycleOwner){
         binding.swiperefreshLayout.isRefreshing = it
    }

    //... observe the rest of your LiveData
} 

编辑:

您可以创建如下函数

private inline fun <T> doObserve(ld: LiveData<T>, crossinline callback: (T) -> Unit) {
    ld.observe(viewLifecycleOwner, { callback.invoke(it) })
}

然后直接调用它

 xxxViewModel.apply {

   doObserve( isRefreshing){
         binding.swiperefreshLayout.isRefreshing = it
    }

    //... observe the rest of your LiveData
}