rx-java Basic Subjects


Example

A Subject in RxJava is a class that is both an Observable and an Observer. This basically means that it can act as an Observable and pass inputs to subscribers and as an Observer to get inputs from another Observable.

Subject<String, String> subject = PublishSubject.create(); 
subject.subscribe(System.out::print);
subject.onNext("Hello, World!"); 

The above prints "Hello, World!" to console using Subjects.

Explanation

  1. The first line of code defines a new Subject of type PublishSubject

    Subject<String, String> subject = PublishSubject.create();
        |     |       |       |                 |
     subject<input, output>  name   = default publish subject
    
  2. The second line subscribes to the subject, showing the Observer behaviour.

    subject.subscribe(System.out::print);
    

    This enables the Subject to take inputs like a regular subscriber

  3. The third line calls the onNext method of the subject, showing the Observable behaviour.

    subject.onNext("Hello, World!"); 
    

    This enables the Subject to give inputs to all subscribing to it.

Types

A Subject (in RxJava) can be of any of these four types:

  • AsyncSubject
  • BehaviorSubject
  • PublishSubject
  • ReplaySubject

Also, a Subject can be of type SerializedSubject. This type ensures that the Subject does not violate to the Observable Contract (which specifies that all calls must be Serialized)

Further reading: