Saturday, November 16, 2019

Reactive Programming: What is it ?

Reactive means : Anything which responds based on some events.

If we go by the name 'Reactive Programming', it means a programming technique where things get executed based on some reactions or in programming terms events drive the execution.

Aren't we familiar with event based execution:

1. We have queues where in case of message arrival, some code get executed or
2. we have listeners which continuously listen to events, like arrival of some message on web sockets to process it.

So aren't we already writing reactive programs ? What is new here ?

The new is the level of complexities involved in the way we write Reactive Programs

1. These old way of reactive coding, we require a dedicated external system like queue for publishing and subscription. You require some sort of dedicated listener who can take care of every message arrival.

2. In case of plain java event based programming we have to block 1 thread which is continuously listening to the events and doing whatever needed.

In nutshell, old way of programming involves many components or wastage of precious resources to achieve reactive programming.

The new Reactive library will do away with this complexities and it provide in build APIs which do the job of reaction :) based on the events.

Whatever may be the paradigm, for reactive programming below three actors are must:

1. Observables : which will emit events called Publisher as well
2. Observers : which will consume events called Subscriber as well
3. Scheduler: which will schedule or control the flow of events




image courtesy: https://medium.com/@kevalpatel2106/what-is-reactive-programming-da37c1611382


Java 9 has a Reactive Stream API to support Reactive Programming. It majorly contains below 4 interfaces :

Publisher.java

public interface Publisher<T>
{
    public void subscribe(Subscriber<? super T> s);
}

Subscriber.java

public interface Subscriber<T>
{
    public void onSubscribe(Subscription s);
    public void onNext(T t);
    public void onError(Throwable t);
    public void onComplete();
}

Subscription.java

public interface Subscription<T>
{
    public void request(long n);
    public void cancel();
}

Processor.java

public interface Processor<T, R> extends Subscriber<T>, Publisher<R>
{
}





No comments: