When to use RxJava in Android and when to use LiveData from Android Architectural Components?
Regarding the original question, both RxJava and LiveData complement each other really well.
LiveData
shines on ViewModel layer, with its tight integration with Android lifecycles and ViewModel
. RxJava
provides more capabilities in transformations (as mentioned by @Bob Dalgleish).
Currently, we're using RxJava
in data source and repository layers, and it's transformed into LiveData
(using LiveDataReactiveStreams
) in ViewModels (before exposing data to activities/fragments) - quite happy with this approach.
Android LiveData is a variant of the original observer pattern, with the addition of active/inactive transitions. As such, it is very restrictive in its scope.
Using the example described in Android LiveData, a class is created to monitor location data, and register and unregister based on application state.
RxJava provides operators that are much more generalized. Let's assume that this observable will provide location data:
Observable<LocationData> locationObservable;
The implementation of the observable can be built up using Observable.create()
to map the call back operations. When the observable is subscribed, the call back is registered, and when it is unsubscribed, the call back is unregistered. The implementation looks very similar to the code provided in the example.
Let's also assume that you have an observable that emits true when the application is active:
Observable<Boolean> isActive;
Then you can provide all the functionality of LiveData by the following
Observable<LocationData> liveLocation =
isActive
.switchMap( active -> active ? locationObservable : Observable.never() );
The switchMap()
operator will either provide the current location as a stream, or nothing if the application is not active. Once you have the liveLocation
observable, there a lot of things you can do with it using RxJava operators. My favorite example is:
liveLocation.distinctUntilChanged()
.filter( location -> isLocationInAreaOfInterest( location ) )
.subscribe( location -> doSomethingWithNewLocation( location ) );
That will only perform the action when the location changed, and the location is interesting. You can create similar operations that combine time operators to determine speed. More importantly, you can provide detailed control of whether operations happen in the main thread, or a background thread, or a multiple threads, using RxJava operators.
The point of RxJava is that it combines control and timing into a single universe, using operations provided from the library, or even custom operations that you provide.
LiveData addresses only one small part of that universe, the equivalent of building the liveLocation
.
There are many differences between LiveData and RxJava:
- LiveData is not a STREAM while in RxJava everything (literally everything) is a STREAM.
- LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
- LiveData is synchronous, So you can't execute a chunk of code (network call, database manipulation etc.) asynchronously using just LiveData as you do with RxJava.
- What best you can do to exploit the most of this duo is to use RxJava for your business logic (network call, data manipulation etc, anything that happens in and beyond Repository) and use LiveData for your presentation layer. By this, you get transformation and stream capabilities for your business logic and lifecycle-aware operation for your UI.
- LiveData and RxJava compliment each other if used together. What I mean is, do everything with RxJava and at the end when you want to update UI, do something like the code given below to change your Observable into LiveData. So, your View (UI) observes to the LiveData in ViewModel where your LiveData is nothing but non-mutable MutableLiveData (or MutableLiveData is mutable LiveData).
- So the question here is, why should you even use LiveData at the first place? As you can see below in the code, you store your response from RxJava to MutableLiveData (or LiveData) and your LiveData is lifecycle-aware, so in a way, your data is lifecycle-aware. Now, just imagine the possibility when your data itself know when and when-not-to update the UI.
- LiveData doesn't have a history (just the current state). Hence, you shouldn't use LiveData for a chat application.
- When you use LiveData with RxJava you don't need stuff like MediatorLiveData, SwitchMap etc. They are stream control tools and RxJava is better at that by many times.
- See LiveData as a data holder thing and nothing else. We can also say LiveData is lifecycle-aware consumer.
public class RegistrationViewModel extends ViewModel {
Disposable disposable;
private RegistrationRepo registrationRepo;
private MutableLiveData<RegistrationResponse> modelMutableLiveData =
new MutableLiveData<>();
public RegistrationViewModel() {
}
public RegistrationViewModel(RegistrationRepo registrationRepo) {
this.registrationRepo = registrationRepo;
}
public void init(RegistrationModel registrationModel) {
disposable = registrationRepo.loginForUser(registrationModel)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Response<RegistrationResponse>>() {
@Override
public void accept(Response<RegistrationResponse>
registrationModelResponse) throws Exception {
modelMutableLiveData.setValue(registrationModelResponse.body());
}
});
}
public LiveData<RegistrationResponse> getModelLiveData() {
return modelMutableLiveData;
}
@Override
protected void onCleared() {
super.onCleared();
disposable.dispose();
}
}