This repository has been archived by the owner on May 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
broadcaster.service.ts
72 lines (67 loc) · 1.7 KB
/
broadcaster.service.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { filter, map } from 'rxjs/operators';
interface BroadcastEvent {
key: any;
data?: any;
}
/**
* Provides detyped notifications of changes in application state.
*
* It is recommended that all components and services broadcast events
* that may be of interest to others. There is no overhead to broadcasting
* an event that no one is subscribed to.
*
* Any events broadcast should be documented as part of the modules API.
*
* Example
* -------
*
* In this example we broadcast an event of type cheese and have the mouse
* subscribe to it.
*
*
* constructor(
* private broadcaster: Broadcaster
* )
*
* ngOnInit() {
* broadcaster.on<Cheese>('cheese').subscribe(val => this.mouse.eatCheese(val));
* }
*
* newCheese() {
* broadcaster.broadcast('cheese', { type: 'cheddar' } as Cheese);
* }
*
*/
@Injectable({
providedIn: 'root'
})
export class Broadcaster {
private _eventBus: Subject<BroadcastEvent>;
constructor() {
this._eventBus = new Subject<BroadcastEvent>();
}
/**
* Broadcast an event.
*
* @param key the key to broadcast the event for. Normally we use a string.
* @param data the payload to send.
*/
broadcast(key: any, data?: any) {
this._eventBus.next({key, data});
}
/**
* Observe an event.
*
* @param key the key to observe the event for.
* @returns an Observable to which you can subscribe or use any RxJS operator.
*
*/
on<T>(key: any): Observable<T> {
return this._eventBus.asObservable()
.pipe(filter(event => event.key === key),
map(event => <T> event.data)
);
}
}