rxjs 中的嵌套和展平有什么区别?

What is the difference between nesting and flattening in rxjs?

我正在使用 redux observable,我有点困惑我是应该在 epics 中嵌套 observables 还是展平它们。

我有一个简单的史诗,它采取一个动作,触发一个承诺,然后等待结果用有效负载触发另一个动作。

这就完成了工作...

export const stageTitleUpdate = action$ =>
  action$.pipe(
    ofType('projects/updateTitle'),
    debounceTime(1000),
    switchMap(
      ({ payload }) => from(later(2000, payload))
    ),
    map(res => fetchFulfilled(res))
  );

我也可以这样写,结果似乎完全一样...

export const stageTitleUpdate = action$ =>
  action$.pipe(
    ofType('projects/updateTitle'),
    debounceTime(1000),
    switchMap(
      ({ payload }) => from(later(2000, payload))
      .pipe(
         map(res => fetchFulfilled(res))
      )
    ),

  );

两者有什么区别吗?这只是文体上的问题,还是将来会以这种方式写另一种方式让我失望?

我学到的一个主要区别是

from(later(2000, payload)) 流被称为内部可观察。

两种样式都有效,但是逻辑内部可观察对象可以让您在内部范围内包含错误并保持源可观察对象流动而不是完成或抛出错误。

Style1 - 如果 from(later(2000, payload)) 或 fetchFulfilled(res) 抛出错误,即使在外部流中使用 catchError,整个流也将停止发射。

export const stageTitleUpdate = action$ =>
  action$.pipe(
    ofType('projects/updateTitle'),
    debounceTime(1000),
    switchMap(
      ({ payload }) => from(later(2000, payload))
    ),
    map(res => fetchFulfilled(res)),
    // this will complete your entire stream
    catchError(e=>of(e))
  );

Style2 - 如果您在内部 observable 中发现错误,源将继续工作

export const stageTitleUpdate = action$ =>
  action$.pipe(
    ofType('projects/updateTitle'),
    debounceTime(1000),
    switchMap(
      ({ payload }) => from(later(2000, payload))
      .pipe(
         map(res => fetchFulfilled(res)),
         catchError(e=>of(e))
      )
    ),
  );

话虽如此,还是要看你的上下游任务,以及上游有什么样的map process(mergeMap,switchMap,exhaustMap)。通常,如果您根据您的业务逻辑自然地进行组合,那么一切都会正常进行。即

const task2=task21().pipe(map(()=>task22())
task1().pipe(switchMap(_=>
   task
))