0

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();
ruth
  • 29,535
  • 4
  • 30
  • 57
Luckyy
  • 1,021
  • 4
  • 15
  • 29
  • can you please how you subscribe to that observable – Alaa M. Jaddou Aug 17 '21 at 05:11
  • hi @AlaaM.Jaddou added more code in the hints at the bottom – Luckyy Aug 17 '21 at 05:15
  • I think the value is still their coz of ```this.text``` variable not from the subscription. you can test that by clarifying the value or testing it by sending any other value from another page. if you get back the subscription will be created again :-( – Alaa M. Jaddou Aug 17 '21 at 05:45

2 Answers2

3

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.

ruth
  • 29,535
  • 4
  • 30
  • 57
0

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);
}
mat.hudak
  • 2,803
  • 2
  • 24
  • 39
  • Yes as an alternative I have done that only. Isn't there any better way to flush the value rather broadcasting a null ? – Luckyy Aug 17 '21 at 05:57