What is the right place to start a service in MVVM architecture Android

Viewed 3396

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:

  • Activity should not know anything about the data and should take care of the views
  • ViewModels should not know about activity
  • Repository is responsible for getting the data

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?

2 Answers

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
    }
}

As far as I know, Services are Android related so, they could be started from View (Activity/Fragment/Lifecycleowner).

Related