Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { of, Observable, merge, BehaviorSubject } from 'rxjs';
- import { switchMap, filter, tap, take, first, delay } from 'rxjs/operators';
- @Injectable({
- providedIn: 'root'
- })
- export class PollingService {
- callBackEnd() {
- const getRandomResponse = () => !!Math.round(Math.random() - 0.3) ? '200' : '204';
- return of(getRandomResponse()).pipe(delay(200));
- }
- getPollingResponse() {
- /**
- * How many calls must be done
- */
- const callLimit = 5;
- /**
- * The initial value is '204' so that we can start both streams
- */
- const someSubjectTrigger$ = new BehaviorSubject('204');
- /**
- * This stream will emit when the `callLimit` is reached, and make new server call
- * upon response with status `204`
- */
- const failureStream$ = someSubjectTrigger$
- .pipe(
- take(callLimit),
- filter(x => x === '204'),
- switchMap(() => this.callBackEnd()
- .pipe(
- tap(x => someSubjectTrigger$.next(x))
- )
- ),
- );
- /**
- * This stream will emit on success
- */
- const success$ = someSubjectTrigger$.pipe(
- filter(x => x !== '204')
- );
- /**
- * Finished stream will emit once on success or on error
- */
- return merge(failureStream$, success$)
- .pipe(
- first()
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement