What is Reactive Java?
Reactive Java is the library that manages sequences of event by using observable sequences. It is currently implemented by Netflix. Here is the demonstration of the RxJava:
In this example, circular item represents an event where event could be click event, caches, variables, data. It ensures that the event is completed before proceed to the next event. Each events can be modified into new form before proceed to the next action. For example, It applies “Map” function to the observable sequences into new form.
Basic Explanation on Observable
Common Usage of RxAndroid
RxAndroid is able to create a subscription that is bound to lifecycle: OnStart, OnPause and OnResume. It subscribes to an observable on “OnStart” and unsubscribes observable on “onPause” and “onDestroy” lifecycle. It is important to do so to avoid NullPointerException. NullPointerException happens if it tries to update the UI which is already destroyed after stream of events is completed.
Whenever there is rotation of screen, the data and activity will be destroyed. RxJava provides feature that always listening to the background sequence which keeps emitting items, and updating UI components, for example Textviews even after screen rotation or detached from the screen.
Implementation of Lifecycle and Listening observable
In OnCreate, start the sequences.
1 2 3 4 5 6 7
In OnViewCreated of the Fragment, do the subscription. It means whenever the view is created, it will subscribe to an observable and continue to update the UI components i.e. TextView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Unsubscribe the observable whenever the view is destroyed/detached due to screen rotation to prevent NPE.
1 2 3 4 5
The following code is to bound the subscription to lifecycle.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15