Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe fires twice when I revisit a page

Tags:

angular

rxjs

I'm running into a scenerio where subscribe fires 2x. However if I get rid of the service by copy pasting the poller method into my component then the issue goes away.

I am running in Ionic 3, but I don't think that matters here. "rxjs": "5.4.3"

unsubscribe() is called on ngDestroy()

my-service.service.ts

public pollingDataReceived = new Subject<any>();

pollForData = (id: string) : Subscription => {
    let stopPollingForStatus = false;
    return Observable.interval(environment['pollingInterval'])
          .takeWhile(() => !stopPollingForStatus)
          .concatMap(() => {
            return this.getAnalysisById(id);
          })
          .subscribe((analysisData) => {
            if (analysisData) {
              if (analysisData.status === 'questions') {
                stopPollingForStatus = false;
              }
              else {
                stopPollingForStatus = true;
                const result = {
                  someData: 'whatever'
                };
                console.log('raise pollingDataReceived event');// This happens ONCE
                this.pollingDataReceived.next(result);
              }
            }
            else {
              alert('no analysis data!');
            }
          });
  }

my.component.ts (a subscriber)


  private pollingData: Subscription;

  someEventHandler() {
    this.pollingData = this.pollForData(this.id);
  }

  ngOnInit(): void {
    this.myService.pollingDataReceived.subscribe((data) => {
        this.analysis = data.analysisData;
        //This is getting called 2x.  Maybe I double subscribed?
        myNavigator.navigateToPageByStatus(myPage);
    }, (err) => { console.log(err); });
    }

  ngOnDestroy() {
    console.log('ngOnDestroy: unsubscribe pollingData in flow');// This does get called
    this.pollingData.unsubscribe();
  }
like image 586
P.Brian.Mackey Avatar asked Jan 01 '23 02:01

P.Brian.Mackey


1 Answers

Angular Services behave like Singletons unless provided at a component level. Hence the pollingDataReceived Subject will continue to hold its subscriptions until the service is in scope.

In your case, the stale subscription to this.myService.pollingDataReceived from from the earlier visit also is getting fired. Hence the subscriber firing twice on revisit.

Cleaning it up on ngDestroy similar to pollingData will fix the issue.

like image 60
ashish.gd Avatar answered Jan 11 '23 22:01

ashish.gd