Getting Started with RxJava

Table of contents
Reading Time: 2 minutes

In this blog, we will learn about the basics of RxJava and its building blocks. RxJava is the open-source implementation of ReactiveX in Java.

What is RX?

RX stands for the Reactive Extension which is used for creating the asynchronous and event-based programs. It is a powerful tool that provides the various benefits. Some of the benefits are it is Composable (RX operators can be combined to produce more complicated operations) and Transformative (RX operator can transform one type of data into another) in nature and even make Error Handling easy.  The basic three constructs of RXJava are:-
1. Observable
2. Subscriber
3. Operator

Observable
An object that emits a stream of data or events. It starts providing data once the subscriber subscribes to it. It is basically of two type:- Blocking and NonBlocking

Subscriber
An object that acts upon the data emitted by Observable. Whenever the Observable emits a new item, the onNext() method is invoked and if the Observable stops emitting the value, the onComplete() method is invoked. And on emitting items, if any error encounters, the onError() method is invoked.

Operator
It helps to transform the data send by the Observable. And there are lots of operators that can be found here in alphabetical order. These operators operate on Observable and simply return Observable and that’s why it can be applied in chaining like one after the other.

Let’s implement some basic example.

Example 1: Creating an Observable using just() operator() and then subscribing it.

Output:

 

Example 2: Creating an Observable from an existing data structure using from() operator and then subscribing it.

 

Output:

 

Example 3: Creating an Observable and transforming it using different operators and then subscribing to it.

 

Output:

 

Conclusion:
So this is pretty straightforward, we create Observable which emits data and it is activated when we will subscribe to it. And if we want to transform the Observable we can use operators.

Hope this is helpful and give you the basic understanding Of RxJava and its basic constructs. Please feel free to provide your suggestions 🙂

References:
https://instil.co/2014/08/05/rxjava-in-different-flavours-of-java/
https://github.com/ReactiveX/RxJava/wiki/Alphabetical-List-of-Observable-Operators

Knoldus-Scala-spark-services-company