【问题标题】:What is the right place to start a service in MVVM architecture Android在 MVVM 架构 Android 中启动服务的正确位置是什么
【发布时间】:2018-04-26 05:10:01
【问题描述】:

我刚开始在 Android 上使用 MVVM 架构。我有一项服务,它基本上会获取一些数据并更新 UI,这就是我从 MVVM 中了解到的:

  • Activity 不应该对数据一无所知,并且应该处理视图
  • ViewModel 不应该知道活动
  • Repository 负责获取数据

现在由于 ViewModels 不应该知道关于活动的任何事情,并且活动不应该做除了处理视图之外的任何事情,谁能告诉我应该在哪里启动服务?

【问题讨论】:

  • 有什么发现或结论吗?
  • 不,我现在从生命周期感知组件启动服务

标签: android mvvm kotlin


【解决方案1】:

在 MVVM 中,理想情况下,启动服务的方法应该在Repository 中定义,因为它负责与数据源交互。 ViewModel 保留Repository 的实例,并负责调用Repository 方法并更新自己的LiveData,它可能是ViewModel 的成员。 View 保留ViewModel 的一个实例,它观察ViewModelLiveData 并相应地更改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
    }
}

【讨论】:

    【解决方案2】:

    据我所知,服务与 Android 相关,因此可以从视图(Activity/Fragment/Lifecycleowner)启动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2010-12-06
      • 2021-08-29
      • 2020-02-28
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多