rxjs 管道和订阅(在主题上)在两个单独的步骤中没有按预期工作

rxjs pipe and subscribe (on a Subject) in two separate steps not working as expected

这让我很头疼...下面的代码确实按预期工作:

const s$ = new Subject<any>();
  s$.pipe(
      switchMap(
        x => {
          debugger;
          return myService.getSth();
        }
      )
    ).subscribe(x => {
    debugger;
  });
  s$.next();

switchMapsubscribe部分的debugger都命中了。
但是如果我把它分开(我想把整个管道的东西移动到单独的库中),switchMap 中的调试器不再被命中,这意味着这个特定示例中的服务不会被调用:

  const s$ = new Subject<any>();
  s$.pipe(
      switchMap(
        x => {
          debugger;
          return myService.getSth();
        }
      )
    );

  // ...

  s$.subscribe(x => {
    debugger;
  });
  s$.next();

我在这里想念什么?

在一个可观察对象(包括一个主题)上调用 .pipe 不会修改该可观察对象的作用,而是生成一个 new 可观察对象。在您的第一个示例中,您调用了该新可观察对象的订阅。在你的第二个例子中,你没有对新的可观察对象做任何事情,然后你订阅了原始的非映射主题。由于没有引用新的可观察对象,它丢失了。

.pipe的结果保存到一个变量,然后订阅那个:

const mapped$ = s$.pipe(
  switchMap(
    x => {
      debugger;
      return myService.getSth();
    }
  )
);

mapped$.subscribe(x => {
  debugger;
});

s$.next();