tdlib-native
Version:
🚀 Telegram TDLib native nodejs wrapper
77 lines (76 loc) • 1.7 kB
JavaScript
import { assert } from "./assert.mjs";
class EventBus {
_subscriptions = /* @__PURE__ */ new Map();
_onComplete = /* @__PURE__ */ new Set();
_completed = false;
/**
*
*
* @param {T} value
* @returns {this}
* @memberof EventBus
*/
emit(value) {
for (const subscription of this._subscriptions.keys()) {
subscription(value);
}
return this;
}
/**
*
*
* @param {Subscription<T>} handler
* @returns {Unsubscribe} {Unsubscribe}
* @memberof EventBus
*/
subscribe(handler) {
assert(!this._completed, "Completed");
const cached = this._subscriptions.get(handler);
if (cached) return cached;
const unsubscribe = () => {
this._subscriptions.delete(handler);
};
this._subscriptions.set(handler, unsubscribe);
return unsubscribe;
}
/**
*
*
* @memberof EventBus
* @returns {void}
*/
complete() {
if (this._completed) return;
this._completed = true;
for (const unsubscribe of this._subscriptions.values()) {
unsubscribe();
}
for (const complete of this._onComplete) {
complete();
this._onComplete.delete(complete);
}
}
/**
*
*
* @returns {Observer<T>}
* @example
* import { Observable } from "rxjs";
*
* const bus = new EventBus<number>();
* const observable = new Observable(bus.toRxObserver());
* // Observable<number>
*/
toRxObserver() {
return (subscriber) => {
this._onComplete.add(() => {
var _a;
return (_a = subscriber.complete) == null ? void 0 : _a.call(subscriber);
});
return this.subscribe((value) => subscriber.next(value));
};
}
}
export {
EventBus
};