smartrx/ts/smartrx.classes.observablemap.ts

74 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-08-05 10:50:37 +00:00
import * as plugins from './smartrx.plugins.js';
import * as rxjs from './smartrx.plugins.rxjs.js';
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
*/
2022-08-05 10:50:37 +00:00
export interface IObservableEventBundle<T> {
subject: rxjs.Subject<any>;
eventRef: T;
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 {
2022-08-05 10:50:37 +00:00
public observableEventEmitterBundleArray = new Array<
IObservableEventBundle<IEventEmitter<unknown>>
>();
public observableEventTargetBundleArray = new Array<IObservableEventBundle<EventTarget>>();
2017-10-26 20:56:01 +00:00
/**
2022-08-05 10:50:37 +00:00
* creates a hot subject if not yet registered for the event.
2017-10-26 20:56:01 +00:00
* In case event has been registered before the same observable is returned.
*/
2022-08-05 10:50:37 +00:00
public getSubjectForEmitterEvent<T>(
emitterArg: IEventEmitter<T>,
eventArg: string
): rxjs.Subject<T> {
const existingBundle = this.observableEventEmitterBundleArray.find((bundleArg) => {
return bundleArg.eventRef === emitterArg && bundleArg.event === eventArg;
});
2017-10-26 20:56:01 +00:00
if (existingBundle) {
2022-08-05 10:50:37 +00:00
return existingBundle.subject;
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);
2022-08-05 10:50:37 +00:00
const emitterSubject = new rxjs.Subject();
emitterObservable.subscribe(emitterSubject);
const newBundle: IObservableEventBundle<IEventEmitter> = {
subject: emitterSubject,
eventRef: emitterArg,
2020-07-12 01:53:32 +00:00
event: eventArg,
2022-08-05 10:50:37 +00:00
};
this.observableEventEmitterBundleArray.push(newBundle);
return newBundle.subject;
}
}
public getSubjectForEventTarget<T>(
eventTargetArg: EventTarget,
eventNameArg: string
): rxjs.Subject<T> {
const existingBundle = this.observableEventTargetBundleArray.find((bundleArg) => {
return bundleArg.eventRef === eventTargetArg && bundleArg.event === eventNameArg;
});
if (existingBundle) {
return existingBundle.subject;
} else {
const emitterSubject = new rxjs.Subject();
const newBundle: IObservableEventBundle<EventTarget> = {
subject: emitterSubject,
eventRef: eventTargetArg,
event: eventNameArg,
};
this.observableEventTargetBundleArray.push(newBundle);
return newBundle.subject;
2017-10-26 20:56:01 +00:00
}
}
}