Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a new BehaviorSubject value without calling next?

I have a need to set the value of my BehaviorSubject without triggering a next call to any subscriptions.

I tried doing this:

this.mySubject = new BehaviorSubject(newVal);

but that removes all of the subscriptions as well.

this.mySubject.value = newVal;

doesn't work because .value is readonly.

Is there any way to accomplish this?

Edit: for those asking why I need to do this...

This is an Ionic 4 app, so there is the root list page that calls 2 other child pages (a detail view and an edit page). The first naviagtion into the view page needs the model that was selected. The list page sets the initial value of this model into the BehaviorSubject, then navigates into the view page. However, the setting of this initial value triggers the refresh of the list, which I don't want to do. I just want to init the value, then listen in case the edit page changes it and THEN refresh my list.

like image 598
Scottie Avatar asked Feb 04 '19 17:02

Scottie


People also ask

What is the difference between BehaviorSubject vs observable?

Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities. An observable can be created from both Subject and BehaviorSubject using subject.

How do I update values in BehaviorSubject?

BehaviorSubject works in the following way: Create an internal subscriptions container. Set the current value kept by the subject to the initial value passed as an argument during instantiation. When a new subscription occurs, add it to the container and emit the current value to the corresponding observer.

What does BehaviorSubject next do?

BehaviorSubjectlink It stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the "current value" from the BehaviorSubject .


1 Answers

I'm curious to know why you would actually want to do this but one option you could consider is to include as part of your value a flag that indicates whether updates should be propagated and then have all of your subscriptions derive from a filtered view of the Subject.

this.mySubject.next({propagate: false, value: 42});

makeObservable() {
   return this.mySubject.pipe(filter(x => x.propagate));
}
like image 183
Jesse Carter Avatar answered Nov 11 '22 14:11

Jesse Carter