Search code examples
androidkotlinrx-androidandroid-architecture-componentsandroid-architecture

LiveData.addSource onChanged event not calling Android


I am working with Android Archi+Retrofit+RxAndroid in Kotlin. I need to update my Data object when get response from server. But livedata.addSource's onChanged is not calling.

I am taking help from Git code:- https://github.com/shahbazahmed1269/AndroidGithubIssues

Here is my code in 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()) }
    )
}

}

My Response from LoginRepository is printing but not from ViewModel class.


Solution

  • Check out the official docs for addSource() method MediatorLiveData reference docs, its written

    onChanged callback will be called only when this MediatorLiveData is active.

    Please make sure that you are observing the loginResponse LiveData in your LifecycleOwner class appropriately.