在MVVM体系结构Android中启动服务的正确位置是什么 [英] What is the right place to start a service in MVVM architecture Android

查看:438
本文介绍了在MVVM体系结构Android中启动服务的正确位置是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在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的实例,并观察ViewModelLiveData并相应地对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中启动服务的正确位置是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆