LiveData.addSource onChanged事件不调用Android

问题描述 投票:2回答:1

我在Kotlin使用Android Archi + Retrofit + RxAndroid。我需要在从服务器获得响应时更新我的​​Data对象。但是livingata.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类。

android kotlin rx-android android-architecture-components android-architecture
1个回答
4
投票

查看其编写的addSource()方法MediatorLiveData reference docs的官方文档

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

请确保您正在观察LifecycleOwner课程中的loginResponse LiveData

© www.soinside.com 2019 - 2024. All rights reserved.