我刚开始在 Android 上使用 MVVM 架构。我有一项服务,它基本上会获取一些数据并更新 UI,这就是我从 MVVM 中了解到的:
- Activity 不应该对数据一无所知,并且应该处理 View
- ViewModel 不应该知道 Activity
- Repository 负责获取数据
现在由于 ViewModels 不应该知道关于 Activity 的任何事情,并且 Activity 不应该做除了处理 View 之外的任何事情,谁能告诉我应该在哪里启动服务?
最佳答案
在 MVVM 中,理想情况下,启动服务的方法应该在 Repository
中定义,因为它负责与数据源交互。 ViewModel
保留 Repository
的实例,并负责调用 Repository
方法并更新自己的 LiveData
ViewModel
的成员。 View
保留 ViewModel
的一个实例,它观察 ViewModel
的 LiveData
并相应地更改 UI。这是一些伪代码,可以让您更好地了解情况。
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
}
}
关于android - 在 MVVM 架构 Android 中启动服务的正确位置是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47265685/