Skip to content

Instantly share code, notes, and snippets.

@wojtrawi
Created October 25, 2019 20:21
Show Gist options
  • Save wojtrawi/630262516c4c91a2b3638ce7db0d08fb to your computer and use it in GitHub Desktop.
Save wojtrawi/630262516c4c91a2b3638ce7db0d08fb to your computer and use it in GitHub Desktop.
import { timer, Observable } from "rxjs";
import { scan, tap, switchMapTo, first } from "rxjs/operators";
function checkAttempts(maxAttempts: number) {
return (attempts: number) => {
if (attempts > maxAttempts) {
throw new Error("Error: max attempts");
}
};
}
export function pollUntil<T>(
pollInterval: number,
maxAttempts: number,
responsePredicate: (res: any) => boolean
) {
return (source$: Observable<T>) =>
timer(0, pollInterval).pipe(
scan(attempts => ++attempts, 0),
tap(checkAttempts(maxAttempts)),
switchMapTo(source$),
first(responsePredicate)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment