Let's say you have a MVVM app with a UI layer, a ViewModel, and a Repository. Say that in your repository, you're getting some data from an API with Single
Retrofit calls, and transforming it into a UI-ready viewstate object.
The way I see it, you have two main choices (assuming you want to use LiveData in the UI layer, I am not including the option of observing Rx types from the UI):
Expose your Rx
Observable
from the repository, andsubscribe()
to it in the ViewModel. In the subscriber'sonNext()
, usesetValue()
to wrap your viewstate object in aMutableLiveData
, and expose that as a non-mutableLiveData
to the UI. Manually dispose the subscription inonCleared()
.Expose your Rx
Observable
from the repository and have the ViewModel subscribe to it withLiveDataReactiveStreams
'sfromPublisher()
, in which case manual disposal is unnecessary, and there is noMutableLiveData
at all. However,LiveDataReactiveStreams
subscribes/unsubscribes wheneverLiveData
becomes active/inactive (aka has at least one observer), so this option would halt all stream processing on every config change, unlike (1) (although, only if theObservable
is cold).
Is this analysis incorrect or incomplete in any way? Are there any other important differences between these two approaches?
ViewModel
do it for you automatically. We have implemented this kind of behaviour in our MVVM arch repository github.com/thefuntasty/mvvm-android – Blaspheme