如何使用我的第一个自定义运算符正确扩展rxjs / Observable

时间:2017-04-23 15:52:52

标签: angular rxjs observable ngrx ngrx-effects

我试图在我的服务调用中使用重试模式(实际上:在ngrx / store中的@Effects),延迟间隔增加。因为我设法为一个电话提出了一个工作代码(即使它看起来没有优化,我也不想在我的问题中关注这个),我现在想把它提取到一个自定义的Observable运算符中,并使用它在我的所有服务电话中反复出现。

根据如何设计新运算符的API /用法以及如何使其被TypeScript识别,我感到空白。

下面的代码肯定不起作用,因为它可能会累积大量问题。

所以,现在我的呼叫/效果如下:

  @Effect()
  loadData$: Observable<Action> = this.actions$
    .ofType(ActionTypes.LOAD_DATA)
    .pluck('payload')
    .switchMap(params => {
      return this.myService.getData(params)
        .map(res => new LoadDataCompleteAction(res))

        // ...and this part would have to be extracted: 
        .retryWhen(attempts => Observable
          .zip(attempts, Observable.range(1, 5))
          .flatMap((n, i) => {
            if (i < 4) {
              return Observable.timer(1000 * i);
            } else {
              throw(n);
            }
          })
        )
    })
    .catch(err => Observable.of(new LoadDataFailed()));

以及我所追求的是,​​能够在其他效果中重用重试部分,并具有类似于下面的模式:

  @Effect()
  loadData$: Observable<Action> = this.actions$
    .ofType(ActionTypes.LOAD_DATA)
    .pluck('payload')
    .switchMap(params => {
      return this.myService.getData(params)
        .map(res => new LoadDataCompleteAction(res))
        .retryWhen(attempts => Observable.retryOrThrow(attempts, maxAttempts)

         // or maybe - that's my design question
         .retryOrThrow(attempts, maxAttempts)
    })
    .catch(err => Observable.of(new LoadDataFailed()));

为简单起见,我们可以假设延迟回调模式(i * 1000)对于整个应用程序都是不变的。

以下代码是我的尝试,但显然不起作用。

declare module 'rxjs/Observable' {
  interface Observable<T> {
    retryOrThrow<T>(attempts: any, max: number): Observable<T>;
  }     
}

Observable.prototype.retryOrThrow = function(attempt, max) {
  console.log('retryOrThrow called');

  return Observable.create(subscriber => {
    const source = this;
    const subscription = source.subscribe(() => {
        // important: catch errors from user-provided callbacks
        try {
          subscriber
            .zip(attempt, Observable.range(1, max + 1))
            .flatMap((n, i) => {
              console.log(n, i);
              if (i < max) {
                return Observable.timer(1000 * i);
              } else {
                throw(n);
              }
            });
        } catch (err) {
          subscriber.error(err);
        }
      },
      // be sure to handle errors and completions as appropriate and send them along
      err => subscriber.error(err),
      () => subscriber.complete());

    // to return now
    return subscription;
  });
};
  1. 我不确定如何为新运算符设计API,这里的语法最合适。
  2. 我不知道如何正确声明新运算符和Observable名称空间或模块,以便TypeScript识别新内容。
  3. 更新了服务电话:

      getMocky(){
        const u = Math.random();
    
        const okUrl = 'http://www.mocky.io/v2/58ffadf71100009b17f60044';
        const erUrl = 'http://www.mocky.io/v2/58ffae7f110000ba17f60046';
        return u > 0.6 ? this.http.get(okUrl) : this.http.get(erUrl);
      }
    

1 个答案:

答案 0 :(得分:4)

我无法直接回答您的问题,因为我不知道如何使用自定义运算符扩展rxjs。

幸运的是,在你的情况下,你(和我)不需要知道。 您真正要问的是如何预先定义一系列运算符以在多个位置重用。

您需要的只是 let-Operator ,而且使用起来非常简单。

首先将要重用的逻辑提取到返回observable的函数中:

function retryOrThrow(maxAttempts, timeout) {
  return (source) =>
    source
      .retryWhen(attempts => Observable
        .zip(attempts, Observable.range(1, maxAttempts + 1))
        .flatMap((n, i) => {
          if (i < maxAttempts) {
            return Observable.timer(timeout * i);
          } else {
            throw (n);
          }
        })
      );
}

使用let

在效果中使用此功能
@Effect()
loadData$: Observable<Action> = this.actions$
  .ofType(ActionTypes.LOAD_DATA)
  .pluck('payload')
  .switchMap(params => {
    return this.myService.getData(params)
      .map(res => new LoadDataCompleteAction(res))
      // inject the pre-defined logic with the desired parameters
      .let(retryOrThrow(5, 1000))
    })
    .catch(err => Observable.of(new LoadDataFailed()));

了解let做什么的最简单方法是查看它source-code。它非常简单,因为它只是将一个给定的函数应用于source-observable。