Advertisement
xapu

Untitled

Dec 7th, 2018
423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { of, Observable, merge, BehaviorSubject } from 'rxjs';
  3. import { switchMap, filter, tap, take, first, delay } from 'rxjs/operators';
  4.  
  5.  
  6.  
  7. @Injectable({
  8. providedIn: 'root'
  9. })
  10. export class PollingService {
  11.  
  12. callBackEnd() {
  13.  
  14. const getRandomResponse = () => !!Math.round(Math.random() - 0.3) ? '200' : '204';
  15.  
  16. return of(getRandomResponse()).pipe(delay(200));
  17. }
  18.  
  19. getPollingResponse() {
  20.  
  21. /**
  22. * How many calls must be done
  23. */
  24. const callLimit = 5;
  25.  
  26. /**
  27. * The initial value is '204' so that we can start both streams
  28. */
  29. const someSubjectTrigger$ = new BehaviorSubject('204');
  30.  
  31. /**
  32. * This stream will emit when the `callLimit` is reached, and make new server call
  33. * upon response with status `204`
  34. */
  35. const failureStream$ = someSubjectTrigger$
  36. .pipe(
  37. take(callLimit),
  38. filter(x => x === '204'),
  39. switchMap(() => this.callBackEnd()
  40. .pipe(
  41. tap(x => someSubjectTrigger$.next(x))
  42. )
  43. ),
  44. );
  45.  
  46. /**
  47. * This stream will emit on success
  48. */
  49. const success$ = someSubjectTrigger$.pipe(
  50. filter(x => x !== '204')
  51. );
  52.  
  53.  
  54. /**
  55. * Finished stream will emit once on success or on error
  56. */
  57. return merge(failureStream$, success$)
  58. .pipe(
  59. first()
  60. );
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement