RxJava - PublishSubject

RxJava - PublishSubject

PublishSubject emits all the items at the point of subscription. This is the most basic form of Subject

Example

public class RxPublishSubject {
 
    public static void main (String args[])
    {
        PublishSubject<Integer> pSubject = PublishSubject.create();
        pSubject.onNext(0);


        pSubject.subscribe(it -> System.out.println("Observer 1 onNext: " + it),
                (Throwable error) -> { }, () -> {},
                on1 -> System.out.println("Observer 1 onSubscribe"));

        pSubject.onNext(1);
        pSubject.onNext(2);


        pSubject.subscribe(it -> System.out.println("Observer 2 onNext: " + it),
                (Throwable error) -> { }, () -> {},
                on1 -> System.out.println("Observer 2 onSubscribe"));

        pSubject.onNext(3);
        pSubject.onNext(4);
    }
}

 

Output

Observer 1 onSubscribe
Observer 1 onNext: 1
Observer 1 onNext: 2
Observer 2 onSubscribe
Observer 1 onNext: 3
Observer 2 onNext: 3
Observer 1 onNext: 4
Observer 2 onNext: 4