Ionic3 Events propagation scope


#1

Hello everyone,
I just started migrating my ionicv1 app to ionic3 and I’m facing little problem about event handling.
I have a lot of services that are broadcasting events globally to the app, to achieve this in ionic3, I am using the Events class from ionic-angular, when i call publish in the same component the event is well handled by the callback sent with subscribe.
But if I trigger publish(eventname) from an injectable provider, the handler in the page component is never triggered.
I wonder if the events are published in a specific component scope ?
Is it possible to broadcast an event from an injectable provider to get it catched by a page component ?
Should I create my own singleton event handler ?

Thanks in advance for your help.

Regards,
Valentin


#2

This sounds as though it could create a lot of overhead. I would recommend that instead you define Subjects, and have pages subscribe to those Subjects if they are interested in that information. That way, a page only listens to streams that are relevant.


#3

Thanks for your answer
Isn’t this the point of Events.subscribe ? What is the difference with the native Subject class ?


#4

#5

Thank you for the information !
Anyone knows why they did not merge the PR and they kept the actual system ?


#6

I don’t know, but I do know that with Stencil driftyco moved to their own change detection mechanism, and event emitters. Maybe they didn’t want to be too close to Angular or rxjs. Personally, I think rxjs is better supported and better coded, because so many eyes have looked at it.

I’ve used Ionic Events to debug things before, and it probably doesn’t matter either way if you only have one or two events. But if you have “a lot” like what you said in the OP, I think BehaviorSubject, etc., has less overhead, and is safer, hence my recommendation. Others might disagree.


#7

Well … finally I managed to make it work with ionic Events, it was not working because of a mistake in a conditionnal statement i made …
Anyway thank you for your help!


#8

@onyrio, I agree on this one. My approach is to create a StateProvider that consists solely of private BehaviorSubjects and public Observables to serve as getters for each.

Any singular pieces of data that I need to access throughout my app are tracked here (booleans and strings) like platform, isInErrorState, userUid, themeString, currentPage, dataLoaded, stuff like that.

Once the # of things that need tracking start adding up this is the best way to stay organized imo