I am not getting the reason to use RxJava in Android and LiveData from Android Architectural Components.It would be really helpful if the usecases and differences between th
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.
Comparing LiveData to RxJava is comparing apples with fruit salads.
Compare LiveData to ContentObserver and you are comparing apples with apples. LiveData effectively being a lifecycle-aware replacement for ContentObserver.
Comparing RxJava to AsyncTask or any other threading tool is comparing fruit salads to oranges, because RxJava helps with more than just threading.
LiveData is a subset of the android architecture components which is developed by the android team.
With the live data and other architecture components, memory leaks and other similar issues are handled by architecture components. Since it is developed by android team, it is the best for android. They also provide updates that handle new versions of Android.
If you only want to use in Android app development, go for the Android architecture components. Otherwise, if you want to use other Java app, like web app, desktop apps, etc., use RxJava
LiveData
as a data holder thing and nothing else. We can also say LiveData is Lifecycle aware consumer. LiveData
is strongly recommended to know the concept of lifecycle and the relative objects LifeCycleOwner/LifeCycle, you get transformation and stream capabilities for your business logic and lifecycle aware operation for your UI.
Rx is powerful tool that enables to solve of problem in an elegant declarative style. It handles business side options or Service Api operations
As you may know in the reactive ecosystem we have an Observable that emits data and an Observer that subscribes( get notified) of this Observable emission, nothing strange is how works the so called Observer Pattern. An Observable "shouts"something, the Observer get notified that Observable shout something in a given moment.
Think to LiveData
as an Observable that allows you to manage the Observers that are in an active
state. In other terms LiveData
is a simple Observable but also takes care of the life cycle.
But let's see the two code cases you request:
A) Live Data
B) RXJava
A)This is a basic implementation of LiveData
1) you usually instantiate LiveData in the ViewModel to maintain orientation change (you can have LiveData that is read only, or MutableLiveData that is writable, so you usually expose outside from the class LiveData)
2) in the OnCreate
method of the Main Activity(not the ViewModel)
you "subscribe" an Observer object (usually an a onChanged method)
3) you launch the method observe to establish the link
First the ViewModel
(owns the business logic)
class ViewModel : ViewModel() { //Point 1
var liveData: MutableLiveData<Int> = MutableLiveData()
}
And this is the MainActivity
( as dumb as possible)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val ViewModelProvider= ViewModelProviders.of(this).get(ViewModel::class.java)
ViewModelProvider.observe(this, Observer {//Points 2 and 3
//what you want to observe
})
}
}
}
B)This is the basic implementation of RXJava
1) you declare an Observable
2) you declare an Observer
3) you subscribe the Observable with the Observer
Observable.just(1, 2, 3, 4, 5, 6) // Point 1
.subscribe(new Subscriber() { //Points 2 & 3
@Override
public void onCompleted() {
System.out.println("Complete!");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Double value) {
System.out.println("onNext: " + value);
}
});
In particular LiveData
is used with Lifecycle
and often with ViewModel
(as we have seen) architecture components. In fact when LiveData
is combined with a ViewModel allows you to keep updated in real time every change in the Observer, so that the events are managed in real time where is needed. To use LiveData
is strongly recommended to know the concept of lifecycle and the relative objects LifeCycleOwner/LifeCycle, also I would suggest you to have a look at Transformations, if you want to implement LiveData
in real life scenarios. Here you can find some use cases from the great commonsware.
To wrap up basically LiveData
is a simplified RXJava
, an elegant way to observe changes across multiple components without creating explicit so called dependency rules between the components, so that you can test much easier the code and make it much more readable.
RXJava, allows you to do the things of LiveData and much more. Because of the extended functionalities of RXJava, you can both use LiveData for simple cases or exploit all the power of RXJava keep using Android Architecture components as the ViewModel, of course this means that RXJava
can be far more complex, just think has hundreds of operators instead of SwitchMap and Map of LiveData(at the moment).
RXJava version 2 is a library that revolutionized the Object Oriented paradigm, adding a so called functional way to manage the flow of the program.
There are many differences between LiveData and RxJava:
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();
}
}