没有调用Android的LiveData.addSource onChanged事件

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

我从Git代码获取帮助: – https://github.com/shahbazahmed1269/AndroidGithubIssues

这是我在Kotlin的代码:

class LoginRepository : BaseRepository() { fun callLoginApi(data: HashMap): LiveData { val liveData: MutableLiveData = MutableLiveData() // 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 lateinit var loginRepo:LoginRepository; init { loginResponse = MediatorLiveData() loginRepo = LoginRepository() } fun callLoginApi(data: HashMap) { // val loginResponse = MediatorLiveData() loginResponse.addSource( loginRepo.callLoginApi(data), { loginResponse -> Log.e("Response model",loginResponse.toString()) } ) } 

}

我从LoginRepository的响应是打印,但不是从ViewModel类。

查看官方文档addSource()方法MediatorLiveData参考文档 ,其书面

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

请确保您正确观察LifecycleOwner类中的loginResponse LiveData

Interesting Posts