Rxjs defer() 但没有在订阅时重新创建 Observable

Rxjs defer() but without re-creating the Observable upon subscription

defer() 上的 documentation 说:

Creates an Observable that, on subscribe, calls an Observable factory to make an Observable for each new Observer.

我如何修改此行为,以便 仅在第一次订阅时创建 Observable,然后其他订阅会订阅同一个?

在我的用例中,我传递给 defer() 的 Observable 工厂将创建一个最初进行 REST API 调用的 Observable,然后定期重复该调用(一个自动刷新其数据的网站定期)。因此,我有一个包含多个消费者的 Angular 模板,它们会在不同时间订阅此 Observable,具体取决于呈现模板的哪些部分以及呈现时间。我不希望模板中的每个新订阅都引起另一个 API 调用,因为这既慢又浪费,我希望它们都使用相同的自动刷新 Observable。

为此,无需更改 defer 函数的行为,相反,您可以在内部 Observable 上使用 shareReplay 运算符来共享来源和订阅重播。

这是使用 defershareReplay 执行此操作的示例:

import { of, defer } from 'rxjs';
import { shareReplay, tap } from 'rxjs/operators';

const httpSub$ = of('Something!').pipe(
  tap(() => console.log('This will be called only once')),
  shareReplay()
);

const deferSub$ = defer(() => {
  console.log('This will be called each time you subscribe to the deferSub$ observable');
  return httpSub$;
});

// All the new subscribers will share the same source of the httpSub$ observable.
deferSub$.subscribe();
deferSub$.subscribe();
deferSub$.subscribe();

注意:一般情况下,这种情况下不需要使用defer,如果只需要return一样Observable 每次都没有将其结果映射到其他任何东西,或将其与另一个 Observable... 等合并