Reactive Programming in Java

Sadil Chamishka
3 min readAug 13, 2019

--

Reactive programming is a programming paradigm that deals with asynchronous data streams (sequences of events) and the specific propagation of change, which means it implements modifications to the execution environment (context) in a certain order.

RxJava is a Reactive Programming library. Reactive Programming is event-based programming. That means reacting to events.

In programs, there are some I/O operations to be handled, like waiting for a result from database operation or waiting for a response from an external API. Blocking until the I/O operations are completed make evil to the program. with asynchronous nature of I/O operations handling, parallelizable can be achieved without paralyzing by blocking for I/O operations.

RxJava is an open-sourced project by Netflix and it was inspired by the .Net ecosystem. The traditional way of handling collections of data is iterate through it which is known as Iterable-Iterator model and it uses a pull mechanism to iterate through the collection. In a reactive way of coding using RxJava, it uses Observable-Observer model which is a push mechanism. Subscribers get subscribed for an input stream and get notifications from the source.

RxJava has 3 major components

  1. Observable — data streams responsible for emitting data. Observers consume those data.
  2. Operators — provides observable to do asynchronous tasks on the data stream.
  3. Schedulers — manage threads for lightweight tasks and heavy tasks.

Observable

Interface Observable<T> contains 3 main methods

  1. onNext(T data) — get notified when a new item is emitted
  2. onCompleted() — when no item is to be emitted, it notifies the observer
  3. onError(Throwable t) — errors propagated back to users through this

Observable Factories

  • just — capture a single item and emit
  • from — emit a list of data
  • create — create an observable (source)

when observable is created onNext,onCompleted,onError methods have to be implemented.

Operators

  1. Map operator — do operations on all of the elements in the data stream.

2. Filter operator — filter out elements form the data stream

Let’s create a simple data stream and get subscribed to that and do some asynchronous operations on it.

The stream emits 3 values, but filter out and do a transformation to the stream using operators. The output stream is printed on the console after the execution.

3. FlatMap operator — takes an emitted item from an observable and unwraps its content into the flattened output observable stream.

if an error occurred it will be propagated through onErrorReturn channel.

Schedulers

threads can be allocated based on the cost of the operation.

--

--

Sadil Chamishka
Sadil Chamishka

Written by Sadil Chamishka

Associate Technical Lead @ WSO2 IAM TEAM

No responses yet