Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. @Effect()
  2. loadData$: Observable<Action> = this.actions$
  3. .ofType(ActionTypes.LOAD_DATA)
  4. .pluck('payload')
  5. .switchMap(params => {
  6. return this.myService.getData(params)
  7. .map(res => new LoadDataCompleteAction(res))
  8.  
  9. // ...and this part would have to be extracted:
  10. .retryWhen(attempts => Observable
  11. .zip(attempts, Observable.range(1, 5))
  12. .flatMap((n, i) => {
  13. if (i < 4) {
  14. return Observable.timer(1000 * i);
  15. } else {
  16. throw(n);
  17. }
  18. })
  19. )
  20. })
  21. .catch(err => Observable.of(new LoadDataFailed()));
  22.  
  23. @Effect()
  24. loadData$: Observable<Action> = this.actions$
  25. .ofType(ActionTypes.LOAD_DATA)
  26. .pluck('payload')
  27. .switchMap(params => {
  28. return this.myService.getData(params)
  29. .map(res => new LoadDataCompleteAction(res))
  30. .retryWhen(attempts => Observable.retryOrThrow(attempts, maxAttempts)
  31.  
  32. // or maybe - that's my design question
  33. .retryOrThrow(attempts, maxAttempts)
  34. })
  35. .catch(err => Observable.of(new LoadDataFailed()));
  36.  
  37. declare module 'rxjs/Observable' {
  38. interface Observable<T> {
  39. retryOrThrow<T>(): Observable<T>;
  40. }
  41. }
  42.  
  43. Observable.prototype.retryOrThrow = function(attempt, max) {
  44. console.log('retryOrThrow called');
  45.  
  46. return Observable.create(subscriber => {
  47. const source = this;
  48. const subscription = source.subscribe(() => {
  49. // important: catch errors from user-provided callbacks
  50. try {
  51. subscriber
  52. .zip(attempt, Observable.range(1, max + 1))
  53. .flatMap((n, i) => {
  54. console.log(n, i);
  55. if (i < max) {
  56. return Observable.timer(1000 * i);
  57. } else {
  58. throw(n);
  59. }
  60. });
  61. } catch (err) {
  62. subscriber.error(err);
  63. }
  64. },
  65. // be sure to handle errors and completions as appropriate and send them along
  66. err => subscriber.error(err),
  67. () => subscriber.complete());
  68.  
  69. // to return now
  70. return subscription;
  71. });
  72. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement