Search code examples
angularrxjsobservableangular10

Deleting stored observable value in angular service


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();

Solution

  • 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.