import { HttpClient } from '@angular/common/http'; import { Subject, Subscription, BehaviorSubject } from 'rxjs'; import { retryWhen, delay, tap, skip } from 'rxjs/operators'; export class StatusCodePoller { http: HttpClient; url: BehaviorSubject; pollFreq: number; okCode: number; stopOnOk: boolean; pollSubscription: Subscription; urlSubscription: Subscription; poll = new Subject(); ok = new Subject(); isPolling = new BehaviorSubject(false); constructor( url: BehaviorSubject, http: HttpClient, pollFreq = 1000, okCode = 200, stopOnOk = true ) { this.url = url; this.http = http; this.pollFreq = pollFreq; this.okCode = okCode; this.stopOnOk = stopOnOk; } start() { this.stop(); if (this.url.value === '') { return; } this.urlSubscription = this.url.pipe(skip(1)).subscribe(() => this.stop()); this.isPolling.next(true); this.pollSubscription = this.http.get(this.url.value, {observe: 'response'}).pipe( retryWhen(errors => errors.pipe( tap( response => { this.poll.next(response); if (response.status === this.okCode) { if (this.stopOnOk) { this.stop(); } this.ok.next(response); } }), delay(this.pollFreq) ))).subscribe(); } stop() { this.isPolling.next(false); if (this.pollSubscription) { this.pollSubscription.unsubscribe(); } if (this.urlSubscription) { this.urlSubscription.unsubscribe(); } } }