2018-10-10 14:44:44 +00:00
|
|
|
import * as plugins from './smartrx.plugins';
|
2022-01-24 06:30:54 +00:00
|
|
|
import * as rxjs from './smartrx.plugins.rxjs';
|
2020-05-27 17:26:32 +00:00
|
|
|
|
|
|
|
export interface IEventEmitter<T = any> {
|
2020-06-26 00:52:51 +00:00
|
|
|
on: (eventNameArg: string, eventHandlerArg: (eventPayload: T) => any) => void;
|
2020-05-27 17:26:32 +00:00
|
|
|
}
|
2020-05-26 00:18:02 +00:00
|
|
|
|
2017-10-26 20:56:01 +00:00
|
|
|
/**
|
|
|
|
* bundles an observable with an emitter
|
|
|
|
*/
|
2020-05-26 00:18:02 +00:00
|
|
|
export interface IObservableEmitterBundle {
|
2022-01-24 06:30:54 +00:00
|
|
|
observable: rxjs.Observable<any>;
|
2020-05-27 17:26:32 +00:00
|
|
|
emitter: IEventEmitter<unknown>;
|
2018-10-10 14:44:44 +00:00
|
|
|
event: string;
|
2017-10-26 20:56:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* manages observables by making sure that only one observable is regsitered per event
|
|
|
|
*/
|
|
|
|
export class Observablemap {
|
2020-05-26 00:18:02 +00:00
|
|
|
public observableEmitterBundleObjectmap = new plugins.lik.ObjectMap<IObservableEmitterBundle>();
|
2017-10-26 20:56:01 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* creates a new observable if not yet registered for the same event.
|
|
|
|
* In case event has been registered before the same observable is returned.
|
|
|
|
*/
|
2020-05-27 17:26:32 +00:00
|
|
|
public getObservableForEmitterEvent<T>(emitterArg: IEventEmitter<T>, eventArg: string) {
|
2022-01-24 02:44:13 +00:00
|
|
|
const existingBundle = this.observableEmitterBundleObjectmap.findSync((bundleArg) => {
|
2018-10-10 14:44:44 +00:00
|
|
|
return bundleArg.emitter === emitterArg && bundleArg.event === eventArg;
|
|
|
|
});
|
2017-10-26 20:56:01 +00:00
|
|
|
if (existingBundle) {
|
2018-10-10 14:44:44 +00:00
|
|
|
return existingBundle.observable;
|
2017-10-26 20:56:01 +00:00
|
|
|
} else {
|
2022-01-24 06:30:54 +00:00
|
|
|
const emitterObservable = rxjs.fromEvent<T>(emitterArg as any, eventArg);
|
2020-05-26 00:18:02 +00:00
|
|
|
this.observableEmitterBundleObjectmap.add({
|
2017-10-26 20:56:01 +00:00
|
|
|
observable: emitterObservable,
|
|
|
|
emitter: emitterArg,
|
2020-07-12 01:53:32 +00:00
|
|
|
event: eventArg,
|
2018-10-10 14:44:44 +00:00
|
|
|
});
|
|
|
|
return emitterObservable;
|
2017-10-26 20:56:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|