首页 > 解决方案 > 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")
        })

有谁能帮忙吗?

标签: androidkotlinandroid-databindingandroid-livedatakotlin-coroutines

解决方案


你在你的主要活动中添加了这个吗?

binding.setLifecycleOwner(this)

推荐阅读