Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic event fires too many times. Incremented by one each time it's triggered?

TL;DR: Subscription event fires too many times.

I have a event set up, that gets fired, when real time data comes in through a socket.

Through console logs I figured out, that the real time data correctly only comes in once. The event that gets fired, when the real time data comes in, also only gets fired once:

console.log("Event publish got fired!");
this.events.publish(EVENTSLUG_STAMP_UPDATE);

I only see this console log once each time the data comes in.

Here comes the weird part: the subscription events triggers multiple times! For each time real time data comes in, it triggers once more.

this.events.subscribe(EVENTSLUG_STAMP_UPDATE, () => {
  console.log("Event gets gets handled!");
  // Do some code here. This code gets done to many times.
});

So first time real time data comes in I see:

Event publish got fired!
Event gets gets handled!

in the console. Second time, I see

Event publish got fired!
Event gets gets handled!
Event gets gets handled!

Third time I see:

Event publish got fired!
Event gets gets handled!
Event gets gets handled!
Event gets gets handled!

And so on. I’m using socket.io for the real time data. But as I said, filling my code with console logs I came to the conclusion, that only the subscribe event triggers multiple times. Incremented by one each time the event gets published again.

Edit

I have found a workaround that works:

this.events.subscribe(EVENTSLUG_STAMP_UPDATE, () => {
  this.navCtrl.setRoot('ScanSuccessPage').then(() => {
    this.events.unsubscribe(EVENTSLUG_STAMP_UPDATE);
  });
});
like image 413
J. Hesters Avatar asked Mar 01 '18 10:03

J. Hesters


2 Answers

So I just spent a little while struggling with this as well. The end result for me was that I had the subscribe() on a component which was getting destroyed and recreated as I navigated around the application, but I did not have an OnDestroy event handler on the component with unsubscribe() so every time it got instantiated it added another subscription handler.

NOTE: you must also pass the same event handler to unsubscribe(), see Ionic2: Unsubscribe Event to Avoid Duplicate Entries?

like image 150
azyth Avatar answered Nov 10 '22 03:11

azyth


Remove it when not more used (sadly it does not use "once")

//handler as property
private handler=(args)=>{...};


...    

events.subscribe(handler); 

...

notMoreNeeded(){//call this when you don't want event is shooted more
    this.events.unsubscribe(handler)
}
like image 45
Luca C. Avatar answered Nov 10 '22 03:11

Luca C.