WOW, we got one more day so its time to make this day awesome by learning something new 🙂.

Hello guys, hope you are doing good. This is our fourth post in series of RxJava2 Android [ part1, part2, part3 ]. Good news is at last we are ready to start work with Rx. We already completed our prerequisites. I will use Java 8 streams for reactiveness before using Rx Java 2 Android Observables. I think we should know Java 8 and I have a feeling by using Java 8 stream API’s, learning curve of Rx Java 2 Android will be more easy.

Motivation:Motivation is same which I share with you in part1. When I started Rx Java 2 Android at that time I don’t know how and where I will use Rx Java Android.Now we know prerequisites but at that time I don’t know anything. So at that time first I started, how to create a Observable from any data or object. Then I learned about which interfaces or may be I can say callbacks called when some thing happen in Observable data. That is going good theoretically but the day when I start working with Rx practically. I am gone. I saw lot of marble diagrams which make sense theoretically but when I try to use, nothing make sense for me :). Biggest issue for me, I am not able to make my thinking as Reactive or Functional Reactive. My background is working with Imperative and OOP languages so that it is difficult for me. I am always asking these questions. Where I will implement and how I will implement. In this post if you follow I can give you 100% guarantee. You will know. How convert imperative code into Rx not optimised but you will know where to start.

Revision:I want to revise all those concepts which we already learn in first three posts[ part1, part2, part3 ] . Because today we will use all these concepts. In part1 we learned Observer Pattern. In part2 we learned Pull vs Push & Imperative vs Reactive. In part3 we learned Functional Interfaces, Default Methods, Higher Order Functions, Side Effects in Functions, Pure Functions, Lambda Expression and Functional Programming. I am going to write (boring material) there definitions. If you already remembered you can skip next part.Functional Interface is an interface having one abstract method.In Java 8 we can define methods in interface these are called Default Methods.A function with at least one parameter of type function or a function that returns function is called a Higher Order Function.Pure Function is a function, where the return value is only determined by its input values, without observable side effects.Lambda expression in computer programming, also called anonymous function, a function (or a subroutine) defined, and possibly called, without being bound to an identifier.

Introduction:Today we are going to declare a war against Rx Java learning curve. In the end I am 100% sure we will won.War Strategy:1. Java 8 Stream ( That give us a very fast start + we know Java 8 as Android Developer )2. Java 8 Stream to Rx Observable3. Rx Java 2 Android Example4. Tips, how convert imperative code to Rx Java 2 Android code

Its time to do a ATTACK according to our strategy. Solders ATTACK.

1. Java 8 Stream:Currently I am using IntelliJ IDE for Java 8 stream. May be you are thinking why I am going to use Java 8 stream which we are not able to use in Android. All those solders who are thinking like this. I am using Java 8 stream due to two reasons. First I know after some years Java 8 is a first class citizen for Android development. So you should know this stream API’s also any body can ask you in interview. Then Java 8 stream is same like Rx Observable in perspective of concept. So why not we learn both things in a one go. Second I have a feeling lot of solders who are like me dump or lazy or not able to grasp concept very easily they will get that concept in minutes. Again I am giving you 100% guarantee. By learning Java 8 stream you will learn Rx in minutes. Its time to start.

Stream:Classes to support functional-style operations on streams of elements, such as map-reduce transformations on collections (docs.oracle).

First question. What is a stream in english language?Answer: a small, narrow river. Or a continuous flow of liquid, air, or gas.In programming I want to convert my data in the form of stream. Its mean if I have a string but I want to do a work with that as a stream what I need to do. I need to create a mechanism in which I will get my data according to definition “a continuous flow of liquid, air, or gas {or data}”. Now question is why I want my data as a stream. Hmm I am giving you one dump example.I have a blue colour water in a glass with mixup of small and big stones as shown below. (Sorry for drawing skills :) )

Now according to our stream definition. I am going to convert that water into stream as shown below.

I shifted my water from one glass to another by converting into stream. Now I want to remove all big stones from my water. So now I am going to make a one filter which will help me to remove these big stones. Big stone filter as shown below.

Now I am going to apply that filter on my water stream. So I will get water without big stones as shown below.

Hurray. Next I want to clean my water from both small and big stones. For that I have big stone filter but I need to create a new filter for small stones. Small stone filter as shown below.

Its time to apply both filters on my water stream as shown below.

Wow. I have a feeling now you guys are getting my point what type of benefit we can get from stream in programming. Next I want to change my colour from blue to black. For that I need to create a water colour converter (mapper) as shown below.

Its time to implement that converter with my filters as shown below.

Now by converting my water into stream I did a lot of things. I remove big stones using filter, small stone by using filter and in the end I converted my water colour from blue to black using converter (map).

This is the same benefit I will get in our programming when I will convert my data into stream. But now I am going to convert our this example into code. The code now I am going to show you is real code. May be this will not work in example but operator and API’s which I am going to use are real which we will use in later real example. So guys focus on concepts not on compilation. By doing this example I have a feeling we will grasp the concepts very easily. One important point I am using Java 8 stream API in this example not Rx API’s. I don’t want to make things difficult but later I will use Rx also.

Guys need your attention here.Here in Java 8 Stream we have a one Functional Interface its name is called Predicate. So when I want to do a filter I need to give this Functional Interface to stream filter function. Now I am going to show you how I will create a BigStoneFilter in our code.

private static Predicate<String> BigStoneFilter = s -> !s.equals("big stone");Here I am using forEach method. For the time being take this function as a for loop on a stream. I am using here only to show you output. Otherwise without this function we already achieved what we are showing in image. Now its time to show you output.

Guys need your attention here.Here in Java 8 Stream we have a one Functional Interface its name is called Function. So when I want to do a conversion I need to give this Functional Interface to a stream map function. Now I am going to show you how I will create a Water colour converter in our code.

Basically first String in Function <generic> is the value which I will get from water and second String in Function <generic> means what I am returning. For more clarification I am writing one converter which will convert integer into String.

Done. Now I am going to revise some things again.filter: In stream we have a method. Which always take a Functional Interface is called Predicate. In which we will write our logic, which will be apply on our data.map: In stream we have a method.Which always take a Functional Interface is called Function. In which we will write our logic to convert our data according to our requirement.

Before going to next topic. I am going to explain you one more thing which confuse me a lot. Like when I say stream() on any data how that work. So for that I am going to take a one example. I have a list of integers. I want to show that on console.

}Now if you compare both codes. What is the difference?In simple words in first code. I am managing for loop on my own.

for (Integer integer : list) { System.out.println(integer); }

but in second example stream (or later I will show you Observable in Rx) will taking care of my loop.

list.stream().forEach(integer -> System.out.println(integer));

I think lot of things are clear its time to go on a real example by using Rx. In this example I will show you stream code and Rx code both together so you can easily grasp the concept in both domains.

2. Java 8 Stream to Rx Observable:I have a list which contain data "Hello World". In images I am taking as a String but In code example I am going to take as a List which is easy to explain on this point.

}}Guys here I am showing you both Java 8 and Android code. From now I will show you only Reactive code from Java 8 and Android not all class code. In the end of the blog post I will share with you code.Again above example:

list.stream(); // Java 8

Observable.fromIterable(list); // Android

So both will give you same result. Now I am going to output integer list.

Observable.fromIterable(list).forEach(s-> Log.i("Android",s)); // AndroidSo in Java 8 any thing I want as a stream. I will use a stream API but in Android I will convert that data into Observable and will get data as stream.Next we need to do a filter Hello World data by 'l' like as shown below.

That is really simple. Same concept which we already used. I gave a one Functional Interface into map. Which basically doing square of the given value and return that square value.

.forEach(value-> Log.i("Android",value+""));

As we know we only can show String in logs. So I converted value integer into String by appending +"" as shown above.

Wow. I can see one more use of map in my example. Guys as you know I am converting my integer into String for showing into Logcat. But now I am going to write a one more Functional Interface for map. Which will convert my integer into String. So its mean no need to append +"" as shown below.

4. How convert imperative code to Rx Java 2 Android code:Here I am going to use a one real world app imperative code block which I will convert into Reactive using Rx Observable. So you can easily know how you can start with Rx in your project. Important point that may be not good approach but you should start so you feel comfortable. I also know I am using some functions like fromArray, fromIterable which I never explained. So for that please try to use as how I am using in examples. I will explain in detail when I will publish my next post of Rx Android. Try to do a hands on practice a lot.

Example:In one of my project. I am using OnBoarding screen. According to UI I need to show dots on my all OnBoarding screens like shown below.

If you saw carefully in image. In ViewPager I need to give black solid dot to the selected screen.In Imperative code:

}In this setDots function. Basically I am going through from every Image and setting a white empty circle and after that I am setting again solid circle on the selected ImageView.

OR

public void setDots(int position) {

Observable.range(0, circleImageViews.size()) .filter(i->i!=position) .subscribe(i->circleImageViews.get(i).setImageResource(R.drawable.white_circle_outline_on_boarding))); circleImageViews.get(position) .setImageResource(R.drawable.white_circle_solid_on_boarding);}In this setDots function. I set to all Imageviews white empty circle except the one which is a selected one.Later I set the solid circle for the selected Imageview.

4. Tips how convert imperative code to Rx code:I am going to write some tips. So you can start work with Rx easily in your current code.1. If we have any loop in code convert that loop into Observable.

for (int i = 0; i < 10; i++) {

}

to

Observable.range(0,10);2. If we have any if condition in imperative code replaced with filter in Rx.

Observable.range(0, 10) .doAfterNext(i-> System.out.println("i")) .flatMap(integer -> Observable.range(0, 10)) .doOnNext(i -> System.out.print("j ")) .subscribe();Here I used one new operator flatMap. Only try to use in a same way how I used in my example. I will explain that in next post.

Conclusion:Good work solders. Today we try to make our self comfortable with Rx Android. We started from diagrams, then we used Java 8 stream API's. Later we converted Java 8 stream to Rx Java 2 Android Observable. Then we try to saw some real world examples where I show you, how you can start work with Rx in your existing project. In the end I gave you some tips how to convert loop into Rx, if into filter, data transformation using map, nested loop converted by using flatMap. Next post Dialogue between Rx Observable and a Developer (Me) [ Android RxJava2 ] ( What the hell is this ) Part5.Hope you enjoy. OK guys BYE BYE.