]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/util/broadcast.service.ts
LP1869898 Holdings responds to broadcasted changes
[Evergreen.git] / Open-ILS / src / eg2 / src / app / share / util / broadcast.service.ts
1 /**
2  * Create and consume BroadcastChannel broadcasts
3  */
4 import {Injectable, EventEmitter} from '@angular/core';
5 import {empty} from 'rxjs';
6
7 interface BroadcastSub {
8     channel: any; // BroadcastChannel
9     emitter: EventEmitter<any>;
10 }
11
12 @Injectable()
13 export class BroadcastService {
14
15     subscriptions: {[key: string]: BroadcastSub} = {};
16
17     noOpEmitter = new EventEmitter<any>();
18
19     listen(key: string): EventEmitter<any> {
20         if (typeof BroadcastChannel === 'undefined') {
21             return this.noOpEmitter;
22         }
23
24         if (this.subscriptions[key]) {
25             return this.subscriptions[key].emitter;
26         }
27
28         const emitter = new EventEmitter<any>();
29         const channel = new BroadcastChannel(key);
30
31         channel.onmessage = (e) => {
32             console.debug('Broadcast received', e.data);
33             emitter.emit(e.data);
34         };
35
36         this.subscriptions[key] = {
37             channel: channel,
38             emitter: emitter
39         };
40
41         return emitter;
42     }
43
44     broadcast(key: string, value: any) {
45         if (typeof BroadcastChannel === 'undefined') { return; }
46
47         if (this.subscriptions[key]) {
48             this.subscriptions[key].channel.postMessage(value);
49
50         } else {
51
52             // One time use channel
53             const channel = new BroadcastChannel(key);
54             channel.postMessage(value);
55             channel.close();
56         }
57     }
58
59     close(key: string) {
60         if (typeof BroadcastChannel === 'undefined') { return; }
61
62         if (this.subscriptions[key]) {
63             this.subscriptions[key].channel.close();
64             this.subscriptions[key].emitter.complete();
65             delete this.subscriptions[key];
66         }
67     }
68 }
69