【问题标题】:LiveData.addSource onChanged event not calling AndroidLiveData.addSource onChanged 事件未调用 Android
【发布时间】:2018-01-03 20:04:01
【问题描述】:

我正在 Kotlin 中使用 Android Archi+Retrofit+RxAndroid。从服务器获得响应时,我需要更新我的数据对象。但是 livedata.addSource 的 onChanged 没有调用。

我正在从 Git 代码中获取帮助:- https://github.com/shahbazahmed1269/AndroidGithubIssues

这是我在 Kotlin 中的代码:-

class LoginRepository : BaseRepository() {

fun callLoginApi(data: HashMap<String, String>): LiveData<LoginResponse> {

    val liveData: MutableLiveData<LoginResponse> = MutableLiveData<LoginResponse>()

//        val call = mApiService.getLoginUser(data)

    mApiService.getLoginUser(data)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    { user ->
                        liveData.value = user
                        Log.e("response", user.toString())
                    },
                    { error ->
                        liveData.value = LoginResponse(error = error.localizedMessage)
                        Log.e("Error", error.message)

                    })
    return liveData
}
}


open class LoginViewModel : ViewModel() {
lateinit var loginResponse : MediatorLiveData<LoginResponse>
lateinit var loginRepo:LoginRepository;
init {
    loginResponse = MediatorLiveData<LoginResponse>()
    loginRepo = LoginRepository()
}

fun callLoginApi(data: HashMap<String, String>) {
//        val loginResponse  = MediatorLiveData<LoginResponse>()

    loginResponse.addSource(
            loginRepo.callLoginApi(data),
            { loginResponse -> Log.e("Response  model",loginResponse.toString()) }
    )
}

}

我的来自 LoginRepository 的响应正在打印,但不是来自 ViewModel 类。

【问题讨论】:

  • 您是否将生命周期所有者附加到您的loginResponse?您能否显示来自您的代码 activity/fragment 从您的视图模型中调用此调用?
  • 我没有使用lifecycleOwner。
  • 我正在从 Activity 调用 mViewModel.callLoginApi(hash)。其中 hash 是数据的 HashMap
  • 您是否在 LifecycleOwner 类中观察 loginResponse?
  • @AmmY 你需要观察loginResponse 来触发它。实时数据需要生命周期所有者,我假设在您的情况下将是您的活动。

标签: android kotlin rx-android android-architecture-components android-architecture


【解决方案1】:

查看addSource() 方法MediatorLiveData reference docs 的官方文档,其书面说明

只有在此 MediatorLiveData 处于活动状态时才会调用 onChanged 回调。

请确保您在 LifecycleOwner 类中适当地观察 loginResponse LiveData。

【讨论】:

  • 很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
相关资源
最近更新 更多