Last active
August 25, 2017 05:12
-
-
Save JSONCODE007/dae5610894a760878412576f4fa8a127 to your computer and use it in GitHub Desktop.
Global event bus for angular > 2 using rxjs observable and replay subject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ReplaySubject} from "rxjs/ReplaySubject"; | |
import {Observable} from 'rxjs/Observable'; | |
import "rxjs/add/operator/filter"; | |
import "rxjs/add/operator/map"; | |
import { Injectable } from '@angular/core'; | |
@Injectable() | |
export class EventBus | |
{ | |
private events: {}; | |
public constructor() | |
{ | |
this.events = {}; | |
} | |
public post(key: any, data?: any): void | |
{ | |
this.addEventIfNotExists(key); | |
if (this.events[key]) | |
{ | |
this.events[key].next({key, data}); | |
} | |
} | |
public on<T>(key: string): Observable<T> | |
{ | |
this.addEventIfNotExists(key); | |
return this.events[key] | |
.asObservable() | |
.filter(event => event.key === key) | |
.map(event => <T>event.data); | |
} | |
public dispose(key: any) | |
{ | |
if (this.events[key] === undefined) | |
{ | |
return; | |
} | |
this.events[key].unsubscribe(); | |
delete this.events[key]; | |
} | |
public getEvents(): {} | |
{ | |
return this.events; | |
} | |
public getEventsCount(): number | |
{ | |
let keys:[] = this.events.keys(); | |
return keys.length; | |
} | |
private addEventIfNotExists(key: string): void | |
{ | |
if (this.events[key] === undefined) | |
{ | |
this.events[key] = new ReplaySubject<EventBusModel>(); | |
} | |
} | |
} | |
interface EventBusModel | |
{ | |
key: any; | |
data?: any; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment