Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a BehaviorSubject

I have a BehaviorSubject that I would like to reset - by that I mean I want the latest value to not be available, just as if it was just created.

I don't seem to see an API to do this but I suppose there is another way to achieve the same result?

My desired behavior is that I need to emit events, and I'd like subscribers to get the latest event when they subscribe - if a particular manager is in a 'started' state. But when this manager is 'stopped' the latest event should not be available (just like if it was never started in the first place).

like image 421
BoD Avatar asked Aug 30 '17 12:08

BoD


People also ask

How do you complete BehaviorSubject?

To trigger complete on the subject do the following: this. myBehavior. complete();

How do I get BehaviorSubject value?

So the only solution that I found to get the value of a BehaviorSubject was: let value; myBehaviorSubject. take(1). subscribe( (e) => value = e );

What is the difference between subject and BehaviorSubject?

A BehaviorSubject holds one value (so we actually need to initialize a default value). When it is subscribed it emits that value immediately. A Subject on the other hand, does not hold a value.

What is RXJS BehaviorSubject?

BehaviorSubject is a variant of a Subject which has a notion of the current value that it stores and emits to all new subscriptions. This current value is either the item most recently emitted by the source observable or a seed/default value if none has yet been emitted.


1 Answers

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); 
like image 168
akarnokd Avatar answered Oct 05 '22 14:10

akarnokd