Search code examples
javaandroidrx-javabehaviorsubject

Restart BehaviorSubject after an error


Wanted behavior:

subject = BehaviorSubject.create(1);
subject.subscribe(number -> print(number), error -> print(error));

subject.onNext(2);
subject.onNext(3);
subject.onError(new RuntimeException("I'm an error"));
subject.onNext(4);
subject.onNext(5);

With this output:

1
2
3
I'm an error
4
5

My problem is that onNext after onError isn't working (and this is intended, following RxJava rules), but I'll need subject to be resilient to errors, while also passing them down the stream (to show the user some feedback).

Is there a way to do this?


Solution

  • If you want onError and onComplete to be disregarded there is the RxRelay library.

    Description:

    Subjects are useful to bridge the gap between non-Rx APIs. However, they are stateful in a damaging way: when they receive an onComplete or onError they no longer become usable for moving data. This is the observable contract and sometimes it is the desired behavior. Most times it is not.

    Relays are simply Subjects without the aforementioned property. They allow you to bridge non-Rx APIs into Rx easily, and without the worry of accidentally triggering a terminal state.