|
| 1 | +import {Observable, Subscription} from "rxjs"; |
| 2 | + |
| 3 | +export interface Sink<T> { |
| 4 | + subscribed: () => boolean; |
| 5 | + emit: (value: T) => void; |
| 6 | + emitAll: (values: Observable<T>) => Promise<void>; |
| 7 | +} |
| 8 | + |
| 9 | +export class EmitAfterUnsubscribeError extends Error { |
| 10 | + public constructor() { |
| 11 | + super("Emitted a value after subscriber unsubscribed"); |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +export function observeAsync<T>(action: (sink: Sink<T>) => Promise<void>): Observable<T> { |
| 16 | + return new Observable<T>(subscriber => { |
| 17 | + let subscribed = true; |
| 18 | + const subscription = new Subscription(() => { |
| 19 | + subscribed = false; |
| 20 | + }); |
| 21 | + |
| 22 | + const emit = (value: T): void => { |
| 23 | + if (subscribed) { |
| 24 | + void subscriber.next(value); |
| 25 | + } else { |
| 26 | + throw new EmitAfterUnsubscribeError(); |
| 27 | + } |
| 28 | + }; |
| 29 | + |
| 30 | + void action({ |
| 31 | + subscribed: () => subscribed, |
| 32 | + emit, |
| 33 | + emitAll: async values => |
| 34 | + new Promise((resolve, reject) => { |
| 35 | + const innerSubscription = values.subscribe({ |
| 36 | + next: value => void emit(value), |
| 37 | + error: (error: unknown) => { |
| 38 | + subscriber.error(error); |
| 39 | + reject(error); |
| 40 | + }, |
| 41 | + complete: () => { |
| 42 | + resolve(); |
| 43 | + subscription.remove(innerSubscription); |
| 44 | + } |
| 45 | + }); |
| 46 | + subscription.add(innerSubscription); |
| 47 | + }) |
| 48 | + }).then( |
| 49 | + () => { |
| 50 | + subscriber.complete(); |
| 51 | + subscription.unsubscribe(); |
| 52 | + }, |
| 53 | + (error: unknown) => { |
| 54 | + subscriber.error(error); |
| 55 | + subscriber.complete(); |
| 56 | + subscription.unsubscribe(); |
| 57 | + } |
| 58 | + ); |
| 59 | + |
| 60 | + return subscription; |
| 61 | + }); |
| 62 | +} |
0 commit comments