问题描述
我刚刚开始在Android上使用 MVVM 架构.我有一个基本上可以获取一些数据并更新UI的服务,这是我从MVVM中了解的信息:
I just started using MVVM architecture on Android. I have a service which basically fetches some data and updates the UI and this is what I understood from MVVM:
- 活动应该对数据一无所知,应该照顾好视图
- ViewModels不应该了解活动
- 存储库负责获取数据
现在,由于ViewModels应该不了解有关活动的任何信息,而Activity除了处理视图之外不应该做任何其他事情,所以有人可以告诉我应该在哪里启动服务吗?
Now as ViewModels should not know anything about the activity and Activities should not do anything other than handling views, Can anyone please tell where should I start a service?
推荐答案
在MVVM中,理想情况下,应该在Repository
中定义启动服务的方法,因为它负责与数据源进行交互. ViewModel
保留Repository
的实例,并负责调用Repository
方法并更新其自己的LiveData
,该LiveData
可能是ViewModel
的成员. View
保留ViewModel
的实例,并观察ViewModel
的LiveData
并相应地对UI进行更改.这是一些伪代码,可以给您带来更好的画面.
In MVVM, ideally, the methods to start a service should be defined in Repository
since it has the responsibility to interact with Data Source. ViewModel
keeps an instance of Repository
and is responsible for calling the Repository
methods and updating its own LiveData
which could be a member of ViewModel
. View
keeps an instance of ViewModel
and it observes LiveData
of ViewModel
and makes changes to UI accordingly. Here is some pseudo-code to give you a better picture.
class SampleRepository {
fun getInstance(): SampleRepository {
// return instance of SampleRepository
}
fun getDataFromService(): LiveData<Type> {
// start some service and return LiveData
}
}
class SampleViewModel {
private val sampleRepository = SampleRepository.getInstance()
private var sampleLiveData = MutableLiveData<Type>()
// getter for sampleLiveData
fun getSampleLiveData(): LiveData<Type> = sampleLiveData
fun startService() {
sampleLiveData.postValue(sampleRepository.getDataFromService())
}
}
class SampleView {
private var sampleViewModel: SampleViewModel
// for activities, this SampleMethod is often their onCreate() method
fun SampleMethod() {
// instantiate sampleViewModel
sampleViewModel = ViewModelProviders.of(this).get(SampleViewModel::class.java)
// observe LiveData of sampleViewModel
sampleViewModel.getSampleLiveData().observe(viewLifecycleOwner, Observer<Type> { newData ->
// update UI here using newData
}
}
这篇关于在MVVM体系结构Android中启动服务的正确位置是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!