android - LiveData.addSource onChanged 事件不调用 Android

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

我正在 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 类。

最佳答案

查看 addSource() 方法的官方文档 MediatorLiveData reference docs , 它写的

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

请确保您正在适本地观察 LifecycleOwner 类中的 loginResponse LiveData

关于android - LiveData.addSource onChanged 事件不调用 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48084383/

相关文章:

android - 使用不同的 Assets 进行调试和发布

java - Android Paho Mqtt - close() 与 close() 对比unregisterResources() - 内存不足错误

java - 使用Java和vert.x在POST请求中获取图像

java - getLifecycle().getState() 在 onStart() 之后仍然是 CREATED

android - 将图像加载异步任务转换为 rxjava,为什么它滞后于 ui?

java - 不同的按钮,相同的导航 Activity ,但导航 Activity 中 fragment 的结果不同

java - 反编译、修改和重新编译android apk

java - onError 未在 RxJava2 中实现错误,即使它已实现

android - Observable<Object> 的可变列表等到它们全部完成并将它们组合成一个 List<Object>

java - 打印源文件的当前内容(在 Android 上使用 Java 或 Kotlin)