【发布时间】:2018-06-18 13:23:34
【问题描述】:
我正在研究架构组件/MVVM。
假设我有一个存储库、一个 ViewModel 和一个 Fragment。我使用Resource 类作为包装器来公开网络状态,就像Guide to architecture components 中所建议的那样。
我的存储库目前看起来像这样(为简洁起见进行了简化):
class MyRepository {
fun getLists(organizationId: String) {
var data = MutableLiveData<Resource<List<Something>>>()
data.value = Resource.loading()
ApolloClient().query(query)
.enqueue(object : ApolloCall.Callback<Data>() {
override fun onResponse(response: Response<Data>) {
response.data()?.let {
data.postValue(Resource.success(it))
}
}
override fun onFailure(exception: ApolloException) {
data.postValue(Resource.exception(exception))
}
})
}
然后在ViewModel中,我也声明了一个MutableLiveData:
var myLiveData = MutableLiveData<Resource<List<Something>>>()
fun getLists(organizationId: String, forceRefresh: Boolean = false) {
myLiveData = myRepository.getLists(organizationId)
}
最后是片段:
viewModel.getLists.observe(this, Observer {
it?.let {
if (it.status.isLoading()) showLoading() else hideLoading()
if (it.status == Status.SUCCESS) {
it.data?.let {
adapter.replaceData(it)
setupViews()
}
}
if (it.status == Status.ERROR) {
// Show error
}
}
})
如您所见,观察者不会被触发会出现问题,因为 LiveData 变量将在此过程中被重置(存储库创建一个新实例)。
我正在尝试找出确保在 Repository 和 ViewModel 之间使用相同 LiveData 变量的最佳方法。
我考虑过将 ViewModel 中的 LiveData 传递给 getLists 方法,以便 Repository 使用 ViewModel 中的对象,但即使它有效,这样做似乎也是错误的。
我的意思是这样的:
视图模型
var myLiveData = MutableLiveData<Resource<List<Something>>>()
fun getLists(organizationId: String, forceRefresh: Boolean = false) {
myRepository.getLists(myLiveData, organizationId)
}
存储库
fun getLists(data: MutableLiveData<Resource<List<Something>>>, organizationId: String) {
...
}
【问题讨论】:
-
您可能正在您的虚拟机中寻找developer.android.com/reference/android/arch/lifecycle/…。
-
为什么不在您的存储库中创建实时数据,然后简单地将其向上传递到您的视图?
标签: android mvvm kotlin android-architecture-components android-livedata