squid-js/src/utils/SubscribableObserver.ts

52 lines
1.4 KiB
TypeScript
Raw Normal View History

2019-04-24 13:25:37 +02:00
export class SubscribableObserver<T, P> {
public completed: boolean = false
2019-08-19 13:21:19 +02:00
2019-06-20 00:20:09 +02:00
private subscriptions = new Set<{
onNext?: (next: T) => void
onComplete?: (complete: P) => void
onError?: (error: any) => void
}>()
2019-04-24 13:25:37 +02:00
2019-11-15 00:00:10 +01:00
public subscribe(
onNext?: (next: T) => void,
onComplete?: (complete: P) => void,
onError?: (error: any) => void
) {
2019-04-24 13:25:37 +02:00
if (this.completed) {
2019-06-20 00:20:09 +02:00
throw new Error('Observer completed.')
2019-04-24 13:25:37 +02:00
}
2019-06-20 00:20:09 +02:00
const subscription = { onNext, onComplete, onError }
2019-04-24 13:25:37 +02:00
this.subscriptions.add(subscription)
return {
2019-06-20 00:20:09 +02:00
unsubscribe: () => this.subscriptions.delete(subscription)
2019-04-24 13:25:37 +02:00
}
}
public next(next?: T): void {
2019-06-20 00:20:09 +02:00
this.emit('onNext', next)
2019-04-24 13:25:37 +02:00
}
public complete(resolve?: P): void {
2019-06-20 00:20:09 +02:00
this.emit('onComplete', resolve)
2019-04-24 13:25:37 +02:00
this.unsubscribe()
}
public error(error?: any): void {
2019-06-20 00:20:09 +02:00
this.emit('onError', error)
2019-04-24 13:25:37 +02:00
this.unsubscribe()
}
2019-06-20 00:20:09 +02:00
private emit(type: 'onNext' | 'onComplete' | 'onError', value: any) {
2019-04-24 13:25:37 +02:00
Array.from(this.subscriptions)
.map((subscription) => subscription[type])
2019-09-09 12:18:54 +02:00
.filter((callback: any) => callback && typeof callback === 'function')
2019-04-24 13:25:37 +02:00
.forEach((callback: any) => callback(value))
}
private unsubscribe() {
this.completed = true
this.subscriptions.clear()
}
}