【问题标题】:Kotlin coroutine + LiveData + DataBinding problemKotlin协程+LiveData+DataBinding问题
【发布时间】: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


【解决方案1】:

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

binding.setLifecycleOwner(this)

【讨论】:

    【解决方案2】:

    您是否已将Binding 与您的实际ViewModel 连接?

    someFragmentActivityBinding.viewModel = myViewModel
    

    【讨论】:

      【解决方案3】:

      这是我的错误。 它运作良好。 有隐藏 TextViews..(View.gone) 的代码(所以我认为数据绑定不能很好地工作)。

      问题解决了。谢谢各位。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        • 1970-01-01
        • 2020-04-12
        • 1970-01-01
        • 2019-12-10
        • 2020-03-23
        • 2021-04-01
        相关资源
        最近更新 更多