Skip to content

Commit

Permalink
Refactor DeferredEventEmitter
Browse files Browse the repository at this point in the history
  • Loading branch information
maxima-net committed Aug 16, 2022
1 parent 50cdbc0 commit c6fbe5c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/clients/webSocket/webSocketAtomexClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export class WebSocketAtomexClient implements AtomexClient {
const updatedOrderBooks = mapWebSocketOrderBookEntryDtoToOrderBooks(entryDtos, this.orderBookProvider);
for (const updatedOrderBook of updatedOrderBooks) {
this.orderBookProvider.setOrderBook(updatedOrderBook.symbol, updatedOrderBook);
(this.events.orderBookUpdated as ToDeferredEventEmitter<string, typeof this.events.orderBookUpdated>).emitDeferred(updatedOrderBook.symbol, updatedOrderBook);
(this.events.orderBookUpdated as ToDeferredEventEmitter<string, typeof this.events.orderBookUpdated>).emit(updatedOrderBook.symbol, updatedOrderBook);
}
}
}
32 changes: 23 additions & 9 deletions src/core/deferredEventEmitter.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
import { EventEmitter, PublicEventEmitter } from './eventEmitter';

export class DeferredEventEmitter<K, T extends readonly unknown[]> extends EventEmitter<T> {
private readonly watchersMap: Map<K, ReturnType<typeof setTimeout>> = new Map();
export class DeferredEventEmitter<K, T extends readonly unknown[]> implements PublicEventEmitter<T> {
private readonly watcherIdsMap: Map<K, ReturnType<typeof setTimeout>> = new Map();
private readonly internalEmitter = new EventEmitter<T>();

constructor(
private readonly latencyMs: number = 1000
) {
super();
) { }

addListener(listener: (...args: T) => void) {
this.internalEmitter.addListener(listener);
return this;
}

removeListener(listener: (...args: T) => void) {
this.internalEmitter.removeListener(listener);
return this;
}

removeAllListeners() {
this.internalEmitter.removeAllListeners();
return this;
}

emitDeferred(key: K, ...args: T) {
const oldWatcherId = this.watchersMap.get(key);
emit(key: K, ...args: T) {
const oldWatcherId = this.watcherIdsMap.get(key);
if (oldWatcherId)
clearTimeout(oldWatcherId);

const watcherId = setTimeout(() => {
this.watchersMap.delete(key);
super.emit(...args);
this.watcherIdsMap.delete(key);
this.internalEmitter.emit(...args);
}, this.latencyMs);

this.watchersMap.set(key, watcherId);
this.watcherIdsMap.set(key, watcherId);
}
}

Expand Down

0 comments on commit c6fbe5c

Please sign in to comment.