【发布时间】: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