带有 switchMap 的嵌套管道中的 distinctUntilChanged

distinctUntilChanged in nested pipe with switchMap

我有一个可观察的流设置如下。我有一个间隔,每两秒轮询一次。然后我 switchMap 进行两个依赖 API 调用(这里用 'of' 来模拟)。之后,我想使用 distinctUntilChanged 来确保最终对象不同。唯一的问题是 distinctUntilChanged 不会触发。

我假设它与我们正在创建新流的事实有关,因此从不收集两个对象进行比较,但我不完全理解。

interval(2000).pipe(
    switchMap(() => loadData()),
  )
  .subscribe(res => console.log(res)); // { name: 'test' } is printed every two seconds

function loadData() {
  return of('API call').pipe(
     mergeMap(numb => of({ name: 'test' })),
     distinctUntilChanged((prev, cur) => {
       console.log('CompareFn'); // This will never fire.
       return JSON.stringify(prev) === JSON.stringify(cur)})
  );
}

Stackblitz:https://stackblitz.com/edit/rxjs-ko6k3c?devtoolsheight=60

在这种情况下,我希望下一个处理程序只打印一个值,因为 distinctUntilChanged 应该在第一个之后停止所有值。

希望能解释为什么它没有像我期望的那样工作。

问题是你的 distinctUntilChanged 是在内部 observable 上运行,而不是在外部……你需要这样做

interval(2000).pipe(
    switchMap(_ => loadData()),
    distinctUntilChanged((prev, cur) => {
       console.log('CompareFn');
       return JSON.stringify(prev) === JSON.stringify(cur);
    })
  )
  .subscribe(res => console.log(res));

function loadData() {
  return of('API call').pipe(
     mergeMap(numb => of({ name: 'test' }))
  );
}

在您之前的设置中,只有一个值达到了 distinctUntilChanged,因为间隔通过切换映射切换到一个新的可观察值。