简体   繁体   English

Kotlin 协程 + LiveData + DataBinding 问题

[英]Kotlin coroutine + LiveData + DataBinding problem

I have a issue using Kotlin coroutine + LiveData + DataBinding problem.我在使用 Kotlin 协程 + LiveData + DataBinding 时遇到问题。

My code is below我的代码在下面

class TempViewModel: ViewModel() {

 val creatorInfo: LiveData<CreatorInfo> = liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
        val data = CreatorInfoSettingRepository.requestCreatorInfo().body()
        emit(data!!)
    }
}

and xml use databinding like this和xml使用这样的数据绑定

 <TextView
      android:text="@{viewModel.creatorInfo.email}" />
 <TextView
      android:text="@{viewModel.creatorInfo.phone}" />

 ....

I checked that fetching data(CreatorInfo) from server(retrofit2) is successful, but data is not applied to UI by databinding.我检查了从服务器(retrofit2)获取数据(CreatorInfo)是否成功,但数据未通过数据绑定应用于 UI。

also when check observing like below, observe block is invoked.也当像下面这样检查观察时,观察块被调用。

viewModel.creatorInfo.observe(fragment, Observer { creatorInfo ->
            Log.d("ssong","test")
        })

Anyone who can help?任何人都可以提供帮助?

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

binding.setLifecycleOwner(this)

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

someFragmentActivityBinding.viewModel = myViewModel

There was my mistake.这是我的错误。 It works well.它运作良好。 There was code that hide TextViews..(View.gone) (So I thought databinding does not work well).有隐藏 TextViews..(View.gone) 的代码(所以我认为数据绑定不能很好地工作)。

Problem is solved.问题解决了。 Thank you guys.谢谢你们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM