Understanding Types of the Rx Java Subject

Reading Time: 2 minutes

What is Subject?

A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX . That acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables. And because it is an Observable, it can pass through the items it observes by re-emitting them. And it can also emit new item. There are four varieties of Subjects designed for particular use cases.

  1. Publish Subject

It emits all the subsequent items of the source Observable at the time of subscription. Here, if a student entered late into the classroom. He just wants to listen from that point of time when he entered the classroom. So,Publish will be the best for this use-case. If the source Observable terminates with an error, the PublishSubject will not emit any items to subsequent observers . But will simply pass along the error notification from the source Observable.

  • Replay Subject

It emits all the items of the source Observable, regardless of when the subscriber subscribes. Here, if a student entered late into the classroom, he wants to listen from the beginning. So, here we will use Replay to achieve this.

  • Behavior Subject

Here, if a student entered late into the classroom. He wants to listen to the most recent things(not from the beginning) being taught by the professor. So that he gets the idea of the context. So, here we will use Behavior. However, if the source Observable terminates with an error, the Behaviour Subject will not emit any items to subsequent observers, but will simply pass along the error notification from the source Observable.

  • AsyncSubject

It only emits the last value of the source Observable(and only the last value) only after that source Observable completes.

Here, if a student entered at any point in time into the classroom . He wants to listen only about the last thing being taught after class is over. So, here we will use Asynch. However, if the source Observable terminates with an error. Async Subject will not emit any items, but will simply pass along the error notification from the source Observable.

Therefore if any of these four cases arrived in the future you can use these subjects.

Scala Future

Written by 

Sumit Agarwal is a Software Consultant having more than 1+ years of experience. He is good at problem-solving skills. He likes to watch football and cricket. He has mainly experience in Java and Mysql.