RxJava with MVVM: MutableLiveData w/ setValue() vs. LiveDataReactiveStreams
Asked Answered
B

0

6

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):

  1. Expose your Rx Observable from the repository, and subscribe() to it in the ViewModel. In the subscriber's onNext(), use setValue() to wrap your viewstate object in a MutableLiveData, and expose that as a non-mutable LiveData to the UI. Manually dispose the subscription in onCleared().

  2. Expose your Rx Observable from the repository and have the ViewModel subscribe to it with LiveDataReactiveStreams's fromPublisher(), in which case manual disposal is unnecessary, and there is no MutableLiveData at all. However, LiveDataReactiveStreams subscribes/unsubscribes whenever LiveData 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 the Observable is cold).

Is this analysis incorrect or incomplete in any way? Are there any other important differences between these two approaches?

Bellboy answered 13/12, 2018 at 23:19 Comment(1)
I think, under following circumstances, this is complete list of possible solutions. I personally use solution no. 1. Actually, there is no need to do disposal of subscribers manually, but let ViewModel do it for you automatically. We have implemented this kind of behaviour in our MVVM arch repository github.com/thefuntasty/mvvm-androidBlaspheme

© 2022 - 2024 — McMap. All rights reserved.