RxJava - AsyncSubject

RxJava - AsyncSubject

AsyncSubject emits only the last value of the Observable and this only happens after the Observable completes

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


        pSubject.subscribe(it -> System.out.println("Observer 1 onNext: " + it),
                (Throwable error) -> { }, () -> System.out.println("Observer 1 onComplete"),
                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) -> { }, () -> System.out.println("Observer 2 onComplete"),
                on1 -> System.out.println("Observer 2 onSubscribe"));

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

        /* This is very important in AsyncSubject  */
        pSubject.onComplete();
    }
}

 

Output

Observer 1 onSubscribe
Observer 2 onSubscribe
Observer 1 onNext: 4
Observer 1 onComplete
Observer 2 onNext: 4
Observer 2 onComplete