Rx-Java in Android App Development!

Srinivasa Rao Makkena
5 min readMar 4, 2020

--

In Android Development, All functionalities associated with main components like Activity, Fragment, Service, Broadcast receiver and Content providers occur in main thread (UI Thread). To perform some long running operations like getting data from networking calls (REST API calls) and database operations etc. should perform on background threads. The reason being for this is to avoid “ANR (Application not responding)” error/crash.

When long running operations are happening in the main thread, if user try to perform some events like button clicks, then android operating system couldn’t respond to this click events as main thread is already processing some work. Then, if main thread is not able to respond within 5-10 sec after click event, it’ll throw ANR error. To avoid this, need to implement this function on the background thread instead of main thread. For doing this, there are many native functionalities provided by android native components like AsyncTask, IntentService, AsyncTaskLoader etc. But, there are some disadvantages using these components. Rx-Java provides operators to handle this super easy.

Rx-Java Advantages

  1. Multi-threading super easy
  2. Rx-Operators can transform one type of data to another
  3. Easily readable code
  4. As it provides a common structure, easy to understand and easy to maintain code etc.

Overview

Rx-Java Overview

Observable emits data only if there is at least one observer subscribed to it.

Example: String greeting=”Good Morning”;

Example code

In the above code, we have both Observable and Observer defined, Observable emit String data of “Good Morning” that observed by Observer and pass it to the Callback methods.

Note : There should be at least one Observer subscribe to Observable to emit data by Observable. (Here, myObservable.subscribe(myObserver)).

How to get multi-threading job done?

Scheduler : To schedule and assign threads to emit and observe data emitted.

Mostly used schedulers in android development are like Schedulers.io() -> For tasks like database interactions, network communication and file system interactions AndroidSchedulers.mainThread() -> This is where user interaction happens. Provided to Rx-Java from Rx-Android

There are other schedulers like,

Schedulers.newThread() -> Generates new thread for each unit of work scheduled.

Schedulers.single() -> This scheduler has a single thread executing task one after another following given order.

Schedulers.trampoline() ->executes tasks following FIFO (First In First Out) basis

Schedulers.computation() -> For CPU intensive tasks

Example:

In this code, We are trying to subscribe some work to do on one thread and observe on another thread.

This can be written as below to make it more readable and can use many operators available provided by RxJava.

What is the purpose of just() operator in the above code. It converts normal object into Observable. There many other operators available with RxJava library.

Rx-Operators

just()

Converts an item into an Observable that emits that item.

Emit object only once, if even it is an array list.

Example1:

Observable<String> o1 = Observable.just(“A”,”B”,”C”);

Emits one by one i.e. will go through onNext() method of Observer 3 times.

Example2:

String [] a = {“A”,”B”,”C”};

Observable<String[]> stringList = Observable.just(a);

Emits whole array at once. So, returning String array.

fromArray()

From array emits only one at a time i.e. If we have 20 items in array, emits one after another up-to 20 items completion.

Example: String [] a = {“A”,”B”,”C”};

Observable<String> str = Observable.fromArray(a);

The difference between this and just() is that it returns one after another i.e Observable<String> and just() return all at once i.e. Observable<String []> from above example.

Range()

It returns an Observable that emits sequence of Integers.

Observable<Integer> value = Observable.range(1,20);

Calls onNext() for 20 times to emit all 20 values.

create()

Can create custom observable i.e. can have more control over what data to emit at what time.

Example:

Here, We can call onNext() on any item or list of items and onComplete() once completed.

ObservableOnSubscribe is functional interface that have subscribe() method, that have instance of ObservableEmitter, that emits events to access in onNext() method.

map()

Transforms items emitted by Observable by applying a function to each item that is being emitted. (Item -> Item)

Example:

Here, This is the functionality to convert place name is Place object to Uppercase i.e. we have taken one object and modified that and returns the same. Here, we are not returning Observable. Takes input as Place and returns Place. What if we want to return Observable<Place>?

flatMap()

It takes input as Object and returns Observable. (Item -> Observable)

Scenario where which is useful is, Suppose I have to get the Place Details response, But we need OAuth authentication token to make this service call as part of security. That means, we need to make Place Details API call with token as an input, to get the Token, we need to make another API call. So, Place Details API call will be observing the Token response.

Example:

There are many other Rx-operators and how to use these in android app development. Will continue those in another part as it will be overwhelming if read all in single article.

Thanks for reading thus far. Please heads up if you like the article.

--

--