For anyone else finding this in the same setup I was in, here's another possible route. We're looking at going from Ionic V3 -> V4 and know we have some headaches in store. One being events deprecated. I decided to look how the ionic-angular implementation of events was set up, and realized I kind of liked it. I made a service mimicking their implementation, hoping that replacing the ionic-angular Events later will be easier.
@Injectable()
export class Events {
private _channels: { [key: string]: ((...args: any[]) => void)[] } = {};
public subscribe(topic: string, handler: (...args: any[]) => void) {
if (!this._channels[topic]) {
this._channels[topic] = [];
}
this._channels[topic].push(handler);
}
public publish(topic: string, ...args: any[]) {
if (this._channels[topic] && this._channels[topic].length) {
this._channels[topic].forEach(handler => handler(...args));
}
}
public unsubscribe(topic: string, handler: ((...args: any[]) => void) = null) {
if (!handler) {
delete this._channels[topic];
}
const index = this._channels[topic].indexOf(handler);
if (index > 0) {
this._channels[topic].splice(index, 1);
}
if (!this._channels[topic].length) {
delete this._channels[topic];
}
}
}
I know this doesn't use Observables, but wanted to offer a different solution for anyone else hoping for a drop-in fix for ionic-angular/events
I simplified / removed some of their code, if there's any concerns let me know.