Reputation: 1031
I have a observable service:
GetInputValueObservableService:
private inputObservable = new BehaviourSubject<string>(null);
setObservable(text) {
this.inputObservable.next(text);
}
getObservable() {
return this.inputObservable;
}
I have a component that sets/gets the input value on a click:
so if I have 'initial text' text showing up in html because inputObservable has null value initially and I click on a button that triggers observable and sets 'new text'
now I navigate to other page and come back it still shows 'new text' may be because inputObservable holds the new text, do I need to reset the value to null also?
I have unsubscribed the observable during onDestory of the component.
May be I am doing it incorrectly? Any Ideas?
Hints: Subscription:
this.sub = this.getInputValueObservableService.subscribe((newText)=>{
this.text = newText
})
onDestroy:
this.sub.unsubscribe();
Upvotes: 0
Views: 1077
Reputation: 31125
The source of the issue is using a BehaviorSubject
. It can hold/buffer the current value and emit it immediately to future subscribers. Instead you could try to use RxJS Subject
. It only starts emitting the notifications to observers that were pushed to it after the subscription.
You could find differences b/n different multi-cast observables here.
Try the following
GetInputValueObservableService
import { Subject, Observable } from 'rxjs';
private inputObservable: Subject<string> = new Subject<string>(); // <-- no default value needed
setObservable(text) {
this.inputObservable.next(text);
}
getObservable(): Observable<string> {
return this.inputObservable.asObservable();
}
Nevertheless the unsubscription in the ngOnDestroy()
must not be removed since without it duplicate subscriptions could occur.
Upvotes: 3
Reputation: 3193
Unsubscribing does not flush the value in observable. It's still there and when you navigate back to component and subscribe again, you'll get the latest value. If you want to do so, just before unsubscribe push a null to the observable.
ngOnDestroy(): void {
yourService.setObservable(null);
this.sub.unsubscribe();
}
// or create a function for that in your service
clearObservable(): void {
this.inputObservable.next(null);
}
Upvotes: 0