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.
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.
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.
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 .
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With