【发布时间】:2020-03-27 22:43:07
【问题描述】:
我在使用 Kotlin 协程 + 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")
})
谁能帮忙?
【问题讨论】:
-
我想你是不是已经尝试从活动观察者那里进行数据绑定了?
-
请添加更多活动代码。
-
CreatorInfi 变了吗?
-
@Dak28 不,我正在使用片段。此外,此代码是由 RxJava 而非协程实现的,并且之前运行良好。所以生命周期和片段链接与数据绑定是对的。
标签: android kotlin android-databinding android-livedata kotlin-coroutines