Created
August 18, 2020 03:01
-
-
Save thedillonb/e6a717d4e61e07f9152e3fbb7dfa26d2 to your computer and use it in GitHub Desktop.
RXJS Work Queue
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 * as rx from 'rxjs'; | |
import { concatMap, onErrorResumeNext, tap } from 'rxjs/operators'; | |
export class WorkQueue<T = unknown> { | |
private queue = new rx.Subject<[rx.Observable<T>, rx.Subscriber<T>]>(); | |
constructor() { | |
this.queue.pipe(concatMap(this.doWork)).subscribe(); | |
} | |
enqueue(work: rx.Observable<T>): rx.Observable<T> { | |
return new rx.Observable<T>((obs) => { | |
this.queue.next([work, obs]); | |
}); | |
} | |
private doWork = ([work, sub]: [rx.Observable<T>, rx.Subscriber<T>]) => { | |
if (sub.closed) { | |
return rx.EMPTY; | |
} | |
return work.pipe( | |
tap({ | |
next: (x) => sub.next(x), | |
error: (x) => sub.error(x), | |
complete: () => sub.complete(), | |
}), | |
onErrorResumeNext(rx.EMPTY) | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment