首页 > 解决方案 > RxJS:沿可观察链传递数据的干净方式?

问题描述

我似乎经常遇到这种情况,我需要沿着一系列流传递数据。换句话说,我有依赖于一个或多个其他可观察对象的输出的可观察对象。

下面是通过一个简单示例实现此目的的 3 种方法,但它们都不像“RxJS”方式。有一个更好的方法吗?

// Method #1 - looks clean, but feels hacky

let firstResponse = null;
performFirstAction().pipe(
  tap(_firstResponse => (firstResponse = _firstResponse)),
  switchMap(_firstResponse => performSecondAction(_firstResponse)),
  switchMap(secondResponse => performThirdAction(firstResponse, secondResponse))
);

// Method #2 - gets ugly real quick as it scales

performFirstAction().pipe(
  switchMap(firstResponse =>
    performSecondAction(firstResponse).pipe(
      map(secondResponse => ({ firstResponse, secondResponse }))
    )
  ),
  switchMap(({ firstResponse, secondResponse }) =>
    performThirdAction(firstResponse, secondResponse)
  )
);

// Method #3 - might as well just use callbacks at this point

performFirstAction().pipe(
  switchMap(firstResponse =>
    performSecondAction(firstResponse).pipe(
      switchMap(secondResponse =>
        performThirdAction(firstResponse, secondResponse)
      )
    )
  )
);

标签: typescriptrxjs

解决方案


最简洁和最易读的方法是将中间 Observable 存储在它们自己的变量中。

const firstResponse$ = performFirstAction();

const secondResponse$ = firstResponse$.pipe(
  switchMap(firstResponse => performSecondAction(firstResponse)),
);

const thirdResponse$ = secondResponse$.pipe(
  withLatestFrom(firstResponse$),
  switchMap((secondResponse, firstResponse) => performThirdAction(firstResponse, secondResponse))
);

推荐阅读