-
Notifications
You must be signed in to change notification settings - Fork 0
/
stickyEventBus.ts
40 lines (34 loc) · 984 Bytes
/
stickyEventBus.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { DefaultEventBus, EventBus } from "./eventBus"
import {
StickySubscribable,
Subscriber,
SubscriptionCanceler,
} from "./subscribable"
/**
* Event bus, which holds the last event sent.
*/
export interface StickyEventBus<T> extends EventBus<T>, StickySubscribable<T> {
}
export class DefaultStickyEventBus<T> implements StickyEventBus<T> {
private readonly innerBus = new DefaultEventBus<T>()
constructor(private innerLastEvent: T) {}
get lastEvent(): T {
return this.innerLastEvent
}
emitEvent = (event: T) => {
// Note: this behavior must be as-is
// before invocation of handler, last event must be updated
this.innerLastEvent = event
this.innerBus.emitEvent(event)
}
addSubscriber = (
subscriber: Subscriber<T>,
emitLastEventToNewSubscriber = true
): SubscriptionCanceler => {
const canceler = this.innerBus.addSubscriber(subscriber)
if (emitLastEventToNewSubscriber) {
subscriber(this.lastEvent, canceler)
}
return canceler
}
}