No Doubt RxJava is getting popular in Android applications development. I have already described a few days back about the Reactive Observable in RxJava. I would be recommended please check this post understanding Java 8 stream and Rx Observable in RxJava2. Today we will learn few very basic concept of RxJava which are using in android application development programming.
What is RxJava: By Official documentation, RxJava is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences. RxJava tries to be very lightweight. It is implemented as a single JAR that is focused on just the Observable abstraction and related higher-order functions.
If you are using RxJava is then it is well and good and else start using this awesome feature as soon as possible. But for the most important thing when and where to use? So In this tutorial, we will do some basic example for practice to understand RxJava concept. Rx Java is designed on Observer pattern. It has Observable and subscription pattern. Observable is emitting the data stream and consumer or subscriber is consuming those data. So when ever change happened in an Observable Object then our subscribers will get notified for an update.
RxJava1 has been updated and comes with new version RxJava2. In RxJava2 the Observable has been updating with a new Flowable concept. Flowable is nothing change from Observable but it has incorporated new feature like handle back pressure on the user interface.
Ok Great 🙂 let’s take few example to use RxJava feature. Suppose I have string data as a statement and I want to convert into the list while splitting with white space. Before doing any code, very first thing we need to add reactive dependency into Gradle file. RxAndroid is providing the scheduler for easy switching between the threads.
compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'io.reactivex.rxjava2:rxjava:2.0.8'
For enabling the lambda feature you need to enable jack compiler and use compatibility of Java 8. Here is a detail for android studio Gradle file.
android { compileSdkVersion 26 buildToolsVersion "26.0.0" defaultConfig { ...................... jackOptions { enabled true } } ..................... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } }
OK, let’s split the word by using the flat map feature and convert into List<String> of that steam. Here do not require to create the List object and add those items into a loop, flatMap() of RxJava2 does nicely. It’s made pretty simple and easy and handled everything on stream only.
public static final String IPSUM_LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sad."; public void splitWords() { List<String> words = Observable .just(IPSUM_LOREM) .flatMap(word -> Observable.fromArray(word.split(" "))) .toList() .blockingGet(); Log.d("BasicRxJava", "size is: "+ words.size()); }
and expecting result is D/BasicRxJava: size is: 9.
Now let’s one more function of RxJava2 which is called map(). Let’s say I will split those string till to length of String then I use map for same.
public void wordLengths() { List<Integer> wordsLengths = Observable .just(IPSUM_LOREM) .flatMap(word -> Observable.fromArray(word.split(" "))) .map(String::length) .toList() .blockingGet(); Log.d("BasicRxJava", "size is: "+ wordsLengths.size()); }
and expecting result is D/BasicRxJava: size is: 9.
Ok now let’s say I want to those words of the String which having length is greater than 4, those words should be added into list others will not. For that I need to use another RxJava function is called filter().
public void minFourLetterWords() { List<String> fourLetterWords = Observable .just(IPSUM_LOREM) .flatMap(word -> Observable.fromArray(word.split(" "))) .filter(word -> word.length() >= 4) .toList() .blockingGet(); Log.d("BasicRxJava", "size is: "+ fourLetterWords.size()); }
and expecting result is D/BasicRxJava: size is: 8.
All that operations are done in the main thread only, But I want some of the tasks should be in a background thread and some of on main thread. Then We need to use Rx Android to switching threads between very easy. Once the task has done, I want to subscribe those data for UI update. In this case, I also want to convert string data to upper case then I need to use map () for conversion letters to uppercase and Disposable object for a subscription. Let’s see by example to clarify.
public void backgroundProcessing() { Disposable subscription = Observable .just(IPSUM_LOREM) .flatMap(s -> Observable.fromArray(s.split(" "))) .map(new Function<String, String>() { @Override public String apply(@NonNull String s) throws Exception { SystemClock.sleep(1000); // Fake long running call return s.toUpperCase(); } }) // Do all the work on a background thread .subscribeOn(Schedulers.computation()) // Observe (deliver) events on the main thread .observeOn(AndroidSchedulers.mainThread()) .subscribe(word -> { Log.d("BasicRxJava", "Got word: " + word); }); // Remember to unsubscribe when done! // subscription.dispose(); }
One thing always is remembered for best practice once your task has been done or completed then do not forget to unsubscribe the subscription to avoid the memory leak.
Ok Now, let’s see one more example of a RxJava2 function which is called zip(). We have wordLength and words here and I want to check every word what is that and what is that length by using zip() operation and after those, I want to subscribe for update?
public void zipping() { Observable<String> wordObservable = Observable .just(IPSUM_LOREM) .flatMap(s -> Observable.fromArray(s.split(" "))); Observable<Integer> wordLengthObservable = wordObservable.map(String::length); Observable.zip(wordObservable, wordLengthObservable, (word, length) -> String.format("%s is %d long", word, length)) .subscribe(wordWithLength -> Log.d("BasicRxJava", wordWithLength)); }
and expected result:
D/BasicRxJava:Lorem is 5 long
D/BasicRxJava: ipsum is 5 long
D/BasicRxJava: dolor is 5 long
D/BasicRxJava: sit is 3 long
D/BasicRxJava: amet, is 5 long
D/BasicRxJava: consectetur is 11 long
D/BasicRxJava: adipiscing is 10 long
D/BasicRxJava: elit, is 5 long
D/BasicRxJava: sad. is 4 long
Wrapping Up: As we have seen that RxJava is awesome because I have a stream that I can do all kind of operation at there very easy and simple way. I would be recommended that do all kind of RxJava2 function practice to make your Reactive strong which will help you much better to build the awesome android application. I will be continuing all other awesome RxJava2 function and feature in my next upcoming part-2 tutorial series. Here is part-2.
If you wondering Kotlin for android then I would be recommended to check all this post of Kotlin Category.
Please do subscribe your email to get every newsletter from this blog and if you feel that this post helps you then do not forget to share and comment below.
Happy coding 🙂
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com