How to reset a BehaviorSubject
Another method of switching the value of an observable on and off is to use switchMap()
to flip between the actual observable and an empty one.
Let's assume you have a manager object, and it has a observable that shows its state. Then,
subjectObservable = manager.getStateObservable()
.switchMap( state -> state == ON ? subject : Observable.never() );
will only emit values while the manager
is in the ON
state.
I assume you want to clear the BehaviorSubject
(because otherwise don't call onComplete
on it). That is not supported but you can achieve a similar effect by having a current value that is ignored by consumers:
public static final Object EMPTY = new Object();
BehaviorSubject<Object> subject = BehaviorSubject.createDefault(EMPTY);
Observable<YourType> obs = subject.filter(v -> v != EMPTY).cast(YourType.class);
obs.subscribe(System.out::println);
// send normal data
subject.onNext(1);
subject.onNext(2);
// clear the subject
subject.onNext(EMPTY);
// this should not print anything
obs.subscribe(System.out::println);