5

I have a Service that loads data from via http request every second.

I am wondering how to implement the service in my current MVVM structure.

A solution I could think of is to:

  1. View calls method from ViewModel
  2. ViewModel calls method from Repository
  3. Start the Service in the Repository and pass in some LiveData, as Repositories should be responsible for data loading.
  4. Update this LiveData in the Service via postValue().
  5. Observe this LiveData in UI and notify the ViewModel of the changes
  6. In ViewModel get the changed LiveData and update the other LiveData for the View accordingly
  7. Stop the Service based on the outcome of step 6

However, I am wondering if there is no better solution with a more direct communication from Service to ViewModel or even from Service to Repository to ViewModel

Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58
Gerke
  • 926
  • 1
  • 10
  • 20
  • Personally, I haven't got chance to implement such scenario yet but if this answer https://stackoverflow.com/a/53552240/10271334 can help you understanding correct implementation. There might be technical difficulty solving this but I'll be here to help you out. – Jeel Vankhede Oct 28 '20 at 09:24
  • I still can't tell an optimal process. However by now I found out, that using step 5 and 6, can be replaced by using ```Transformations.map()``` in the viewmodel. – Gerke Mar 10 '21 at 11:18

0 Answers0