首页 > 解决方案 > 与数据绑定一起使用时,LiveData 或 StateFlow 会跳过一些状态

问题描述

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="viewmodel"
            type="com.example.MyViewModel" />
    </data>
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/llNoDataLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:executionResult="@{viewmodel.state}"/>
</layout>
class MyViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle
): ViewModel(){
    private val _state = MutableStateFlow<ExecutionResult<List<glucometerData>>>(ExecutionResult.idle())
    val state: StateFlow<ExecutionResult<List<glucometerData>>> = _state

}
@BindingAdapter("executionResult")
fun View.visibility(state: ExecutionResult<List<Data>>?){
    println("View.visibility:: Execution Result: state: $state")
    when(state){
        is ExecutionResult.Data -> {
            this.isVisible = state.data.isNotEmpty()

        }
        is ExecutionResult.Error -> {

        }
        is ExecutionResult.Idle -> {

        }
        is ExecutionResult.Loading -> {
            when(state.isLoading){
                true -> this.isVisible = false
            }
        }
    }
}

我正在从存储库中获取数据。它将按以下顺序设置执行结果:progress = true,data,progress = false。在绑定适配器中,我只得到空闲状态和进度=假。中间状态的其余部分被跳过。如果我用 LiveData 替换 StateFlows,也会发生同样的事情

标签: kotlin-coroutinesandroid-databindingandroid-lifecycleandroid-viewmodelkotlin-stateflow

解决方案


推荐阅读