2016-08-26 17:37:59 +03:00
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
|
import { Subject } from 'rxjs/Subject';
|
2016-05-13 13:34:55 +03:00
|
|
|
|
|
|
|
|
@Injectable()
|
2016-08-26 17:37:59 +03:00
|
|
|
export class GlobalState {
|
2016-05-13 13:34:55 +03:00
|
|
|
|
|
|
|
|
private _data = new Subject<Object>();
|
|
|
|
|
private _dataStream$ = this._data.asObservable();
|
|
|
|
|
|
2016-08-26 17:37:59 +03:00
|
|
|
private _subscriptions: Map<string, Array<Function>> = new Map<string, Array<Function>>();
|
2016-05-13 13:34:55 +03:00
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
|
this._dataStream$.subscribe((data) => this._onEvent(data));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
notifyDataChanged(event, value) {
|
|
|
|
|
|
|
|
|
|
let current = this._data[event];
|
2016-08-26 17:37:59 +03:00
|
|
|
if (current !== value) {
|
2016-05-13 13:34:55 +03:00
|
|
|
this._data[event] = value;
|
|
|
|
|
|
|
|
|
|
this._data.next({
|
|
|
|
|
event: event,
|
|
|
|
|
data: this._data[event]
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-08-26 17:37:59 +03:00
|
|
|
subscribe(event: string, callback: Function) {
|
|
|
|
|
let subscribers = this._subscriptions.get(event) || [];
|
2016-05-13 13:34:55 +03:00
|
|
|
subscribers.push(callback);
|
|
|
|
|
|
|
|
|
|
this._subscriptions.set(event, subscribers);
|
|
|
|
|
}
|
|
|
|
|
|
2016-08-26 17:37:59 +03:00
|
|
|
_onEvent(data: any) {
|
|
|
|
|
let subscribers = this._subscriptions.get(data['event']) || [];
|
2016-05-13 13:34:55 +03:00
|
|
|
|
|
|
|
|
subscribers.forEach((callback) => {
|
|
|
|
|
callback.call(null, data['data']);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|