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

Hi everyone :slight_smile:

TLDR: 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 subscriptoin evets 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.

Any help would be appreciated!

Looks like you’re subscribing multiple times to the events. Where exactly do you subscribe?

1 Like

That was it! I just call unsubscribe after the event’s subscription has fired!

If events are used to communicate between 2 components, Ex Component B is triggering event and A is subscribing it. If you unsubscribe it from A then event will not work at all. Can you elaborate how you fixed it ?