ViewModel 中的getMoreData()
是从 ViewModel 外部调用的,每次用户滚动到 RecyclerView 的底部时。
存储库中的fetchMore()
返回一个包含LoadingStatus
对象的 LiveData,其中包含加载/成功/失败和错误消息
如何在 ViewModel 中设置loadingStatus
变量,以便片段可以正确观察它?
注: 当用户向下滚动时,可以多次调用 ViewModel 中的getMoreData()
。
ViewModel{
val loadingStatus
fun getMoreData(){
repository.fetchMore()
}
}
Repository{
fun fetchMore() : LiveData<LoadingStatus>{
}
}
Fragment{
viewModel.loadingStatus.observe()
}
问题在于需要一个生命周期所有者来观察存储库中的 LiveData。
首先,您不希望每次调用fetchMore()
时都返回新LiveData<LoadingStatus>
。这将每次创建一个新的LiveData。最好的情况是,你会希望函数fetchMore()
做一些类似的事情,更新单个 LiveData:
Repository{
val status = LiveData<LoadingStatus>()
fun fetchMore() {
status.postValue(LOADING)
// Pseudo code for actually loading more items
status.postValue(FINISHED LOADING)
}
}
但是,您将遇到从ViewModel
观察status
的问题,因为它本身不是生命周期实现,因此它无法轻松地从存储库中观察 LiveData。
我的建议是这样的:
ViewModel{
val loadingStatus: MutableLiveData<LoadingStatus>
init{
repository.observeStatus()
.subscribe( event -> loadingStatus.postValue(event))
}
fun getMoreData(){
repository.fetchMore()
}
}
Repository{
val status = BehaviorSubject.create<LoadingStatus>()
fun observeStatus(): Observable<LoadingStatus> {
return status
}
fun fetchMore(){
status.onNext(LOADING)
// Pseudo code for actually loading more items
status.onNext(FINISHED LOADING)
}
}
Fragment{
viewModel.loadingStatus.observe()
}
请注意,您必须在 ViewModel onCleared 中处置订阅。
请注意,所有这些都是伪代码,应该比这干净得多。