Created
May 18, 2019 12:45
-
-
Save vitaly-t/fcaf95c51e2a3a8d160e41b9173854ae to your computer and use it in GitHub Desktop.
This file contains hidden or 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 {Subject} from 'rxjs'; | |
interface CountedSubscription { | |
unsubscribe: () => void | |
} | |
export type CountParams = { | |
newCount: number, | |
prevCount: number | |
}; | |
export class CountedSubject<T = any> { | |
private count: number = 0; | |
private sub: Subject<T> = new Subject<T>(); | |
public readonly onCount: Subject<CountParams> = new Subject<CountParams>(); | |
public subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): CountedSubscription { | |
const s = this.sub.subscribe(next, error, complete); | |
this.addCount(1); | |
return { | |
unsubscribe: () => { | |
s.unsubscribe(); | |
this.addCount(-1); | |
} | |
}; | |
} | |
public next(value?: T) { | |
this.sub.next(value); | |
} | |
private addCount(add: number) { | |
const prevCount = this.count; | |
const newCount = prevCount + add; | |
this.count = newCount; | |
this.onCount.next({newCount, prevCount}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment