import { Injectable } from '@angular/core' ; import { Subject } from 'rxjs/Subject' ; import { Subscription } from 'rxjs/Subscription' ; import { EventBase } from './event-base' ; @ Injectable ( ) export class PubSubEvent < T > extends EventBase { protected source = new Subject < T > ( ) ; protected observable = this . source . asObservable ( ) ; protected subscriptions : Array < [ ( a : T ) => void , Subscription ] > = [ ] ; subscribe ( observer ) { if ( this . subscriptions . find ( item => item [ 0 ] === observer ) !== undefined ) { return ; } const subscription = this . observable . subscribe ( observer ) ; this . subscriptions . push ( [ observer , subscription ] ) ; } publish ( payload ) { this . source . next ( payload ) ; } unsubscribe ( observer ) { const foundIndex = this . subscriptions . findIndex ( item => item [ 0 ] === observer ) ; if ( foundIndex > - 1 ) { const subscription = this . subscriptions [ foundIndex ] [ 1 ] ; subscription . unsubscribe ( ) ; this . subscriptions . splice ( foundIndex , 1 ) ; } } }