smartrx/ts/smartrx.classes.observablemap.ts

43 lines
1.3 KiB
TypeScript
Raw Normal View History

import * as plugins from './smartrx.plugins';
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 {
observable: plugins.rxjs.Observable<any>;
2020-05-27 17:26:32 +00:00
emitter: IEventEmitter<unknown>;
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) {
2020-07-12 01:53:32 +00:00
const existingBundle = this.observableEmitterBundleObjectmap.find((bundleArg) => {
return bundleArg.emitter === emitterArg && bundleArg.event === eventArg;
});
2017-10-26 20:56:01 +00:00
if (existingBundle) {
return existingBundle.observable;
2017-10-26 20:56:01 +00:00
} else {
2020-05-27 17:26:32 +00:00
const emitterObservable = plugins.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,
});
return emitterObservable;
2017-10-26 20:56:01 +00:00
}
}
}