RxJS - 如何共享昂贵的 observable 的输出,但如果在 N 秒后再次请求它,则重新运行该 observable?

Ghe*_*Ace 6 javascript typescript rxjs6

假设我们有这个全局常量:

const isSignedIn = fromPromise(fetch('/api/is-signed-in'))
    .pipe(throttleTime(1000), shareReply(1));
Run Code Online (Sandbox Code Playgroud)

页面加载后,几个组件会同时订阅这个:

isSignedIn.subscribe(() => console.log('do 1st'));
isSignedIn.subscribe(() => console.log('do 2nd'));
isSignedIn.subscribe(() => console.log('do 3rd'));
Run Code Online (Sandbox Code Playgroud)

以上只会调用 API 一次,但是如果另一个组件订阅它,我需要它再次调用 API(即 1 秒后)。

isSignedIn.subscribe(() => console.log('button press'));
Run Code Online (Sandbox Code Playgroud)

我如何使用 RxJS?

Bug*_*ggy 0

编辑:答案是错误的。BufferSize 是最后 N 个事件重播的时间。此后流就完成了。

signature: shareReplay(
  bufferSize?: number,
  windowTime?: number,
  scheduler?: IIScheduler
):Observable

@param {Number} [bufferSize=Number.POSITIVE_INFINITY] Maximum element count of the replay buffer.
@param {Number} [windowTime=Number.MAX_VALUE] Maximum time length of the replay buffer in milliseconds.
Run Code Online (Sandbox Code Playgroud)

尝试将1000第二个参数添加到 shareReply:

const isSignedIn = fromPromise(fetch('/api/is-signed-in'))
    .pipe(throttleTime(1000), shareReplay(1, 1000));
Run Code Online (Sandbox Code Playgroud)

shareReplay.ts - 请注意refCount--取消订阅,因为它可能会触发其他请求。