android - Kotlin协程+LiveData+DataBinding问题
问题描述
我在使用 Kotlin coroutine + LiveData + DataBinding 时遇到问题。
我的代码如下
class TempViewModel: ViewModel() {
val creatorInfo: LiveData<CreatorInfo> = liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
val data = CreatorInfoSettingRepository.requestCreatorInfo().body()
emit(data!!)
}
}
和 xml 使用这样的数据绑定
<TextView
android:text="@{viewModel.creatorInfo.email}" />
<TextView
android:text="@{viewModel.creatorInfo.phone}" />
....
我检查了从服务器(retrofit2)获取数据(CreatorInfo)是否成功,但数据未通过数据绑定应用于 UI。
当像下面这样检查观察时,也会调用观察块。
viewModel.creatorInfo.observe(fragment, Observer { creatorInfo ->
Log.d("ssong","test")
})
有谁能帮忙吗?
解决方案
你在你的主要活动中添加了这个吗?
binding.setLifecycleOwner(this)
推荐阅读
- eigen - 使用 Eigen 到四元数的角度轴
- c++ - 模拟没有 RTTI 的动态投射
- python - 如何在python中循环遍历二维数组(跳过几行)?
- mysql - 从多行返回数据作为查询中的单独字段
- python-3.x - Python 与 BigQuery FarmHash 有时不相等
- javascript - 如何对调用其他函数的函数进行单元测试?
- python - 如何使用 Python 将子网关联到 Azure 中的网络安全组?
- docker - 无法连接到主机中的 minikube 服务
- flutter - 无法从捕获的文本文件中捕获翻译的文本
- apache-spark - 如何正确分隔列