kotlin-coroutines - 与数据绑定一起使用时,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,也会发生同样的事情
解决方案
推荐阅读
- c++ - 获取指向 vkGetSwapChainImagesKHR 对象向量的指针
- jquery - 为什么我在 VS2019 中安装 JQuery 3.5.1 时收到消息:不兼容:用户 Bower 而不是
- c++ - 如何在 macOS 终端上执行 Qt 应用程序?
- python - TypeError:str() 最多接受 1 个参数(给定 2 个)并且 TypeError:需要一个整数
- java - 使用非默认舍入模式将 long 转换为 double
- vba - 在 MS word 中转换大小写
- mongodb - 带有 MongoDB-4.0 的 Apache Kafka 的官方 MongoDB 源连接器
- r - 刚刚下载了 R 版本 4.0.0 并且无法使用?
- java - 我该如何处理这个错误“在任何可用的数据中心中找不到合适的主机。”?
- vue.js - Route.push 在第二次尝试中无法正常工作