Injectable Atomic Event Emitter using RxJS
JS
S
JavaScriptAn atomic EventEmitter demonstrating an injection of the service as singleton into the 2 apps, the subscription to the observable, one explicit unsubscription (from app1) and an implicit unsubscription (from app2), when the event emitter closes it's stream removing all attached observers.
1// injectable_service.js
2// --------------------------------------------------------------
3import { Subject } from 'rxjs/Rx';
4// import Rx from 'rxjs/Rx';
5/*
6 ES7 Observable spec, the API has changed for observables.
7 onNext -> next
8 onError -> error
9 onCompleted -> complete
10*/
11class InjectableService {
12 constructor(){
13 this._subject = new Subject();
14 this.startEmitting();
15 this.autoStop();
16 console.info('injectable service created');
17 }
18 getObservable(){
19 return this._subject;
20 }
21 startEmitting(){
22 setInterval(()=>{
23 this._subject.next('foo');
24 },2000);
25 }
26 autoStop(){
27 setTimeout(()=>{
28 console.warn('Stream terminated');
29 this._subject.complete();
30 this._subject.next('bar');
31 },7000);
32 }
33}
34const singleton = new InjectableService();
35export default singleton;
36
37// app1.js
38// --------------------------------------------------------------
39import InjectableService from './injectable_service';
40class App1 {
41 constructor(){
42 console.info('App1 running');
43 this._observable = InjectableService.getObservable();
44 const subscription = this._observable.subscribe((data) => {
45 console.log('App 1 Subscribed and its consuming data: ' + data);
46 });
47
48 // Auto unsubscribe
49 setTimeout(()=>{
50 subscription.unsubscribe();
51 },5000);
52 }
53}
54export { App1 };
55
56// app2.js
57// --------------------------------------------------------------
58import InjectableService from './injectable_service';
59class App2 {
60 constructor(){
61 console.info('App2 running');
62 this._observable = InjectableService.getObservable();
63 const subscription = this._observable.subscribe((data) => {
64 console.log('App 2 Subscribed and its consuming data: ' + data);
65 });
66 }
67}
68export { App2 };
69
70// entry.js
71// --------------------------------------------------------------
72'use strict';
73import { Subject } from 'rxjs/Rx';
74import Styles from './styles/index.scss';
75import {App1} from './app_one';
76import {App2} from './app_two';
77
78(() => {
79 console.info('Ecosystem running');
80 const app1 = new App1;
81 const app2 = new App2;
82})();Created on 6/28/2017