0

I have in my Angular 9 Project (rxjs v. 6.5.4) a code like:

export class MyServiceService {
   private myBS = new BehaviorSubject<SomeObject>(null);
   public myBS$ = this.myBS.asObservable();
   setMyBS(value: SomeObject): void {
      this.myBS.next(value);
   } 
}

export class Class1 {
   constructor(private myServiceService: MyServiceService) {}
   myServiceServiceSub = myServiceService.subscribe(result => {
       // Every time I leave the component and enter it again, this part will be called +1 time more
   });
}

export class Class2 {
   constructor(private myServiceService: MyServiceService) {}
   someMethod() {
       myServiceService.setMyBS(someValue);
   }
}

As described, every time if I leave the page including component (Class1) and enter it again, the part within the subscription will be called +1 time more. So if I 5 time leave and enter the page, the code within the subscription will be called 5 times.

I've found out, i have to unsubscribe the Observable by destroying the component. But I cannot understand, why it calls the subscription multiple times, since the component will be destroyed by leaving the page and create a new instance by entering?

Jimy Weiss
  • 568
  • 1
  • 9
  • 25
  • Have a look at the answer, https://stackoverflow.com/questions/57007118/do-i-need-to-complete-takeuntil-subject-inside-ngondestroy it will give you better understanding – Goga Koreli Apr 17 '20 at 19:01
  • 1
    Every time you leave the page the component is destroyed so If you go back to the page it has to create a new one, execute the constructor and subscribe again. The new subscription is different from the previous. So take a look at the link given by @GogaKoreli – Lievno Apr 18 '20 at 21:07
  • @Lievno i understand, that the component is destroyed and exactly that's my question: Why is the new instance multiple times triggered? For my understanding the trigger for the older instance-observers should land in nirvana because they are destroyed and have nothing to do with the new instance. – Jimy Weiss Apr 20 '20 at 09:29
  • They are not destroyed, the component is destroyed but the subscription is still there. If you do not unsubscribe a "hot observable" it stays alive. – Lievno Apr 20 '20 at 19:57
  • @Lievno yes, but the new instance of the component has nothing to do with the subscriptions created by older instances. – Jimy Weiss Apr 21 '20 at 22:37
  • 1
    But your service is not destroyed and keep the reference of your observable so all the subscriptions from your component. Did you read the post provided by @GogaKoreli? – Lievno Apr 22 '20 at 06:54

0 Answers0