RxJS 概念帮助:访问和刷新令牌、非同时刷新

RxJS conceptual help: access and refresh tokens, non-simultaneous refresh

我是 RxJS 的新手,正在寻求有关如何处理以下过程的概念性帮助:

  1. 后端使用短期 JWT 访问令牌进行保护。身份验证后,客户端将获得初始访问令牌和长期刷新令牌。刷新令牌可用于创建新的访问令牌。
  2. 客户端可以解码令牌并且知道令牌是否过期。客户端应在过期时延迟刷新访问令牌;不重试失败的请求。
  3. 客户端不能同时发出多个刷新请求。

我挣扎的最后一部分。我想象一个信号量,或某种 "gate":

我发现 this code 使用 redux 来实现门。有必要吗?

或者,门可以通过 BehaviorSubject 实现吗?

我找到了解决办法!代码可用 here.

使用 BehaviorSubject 让一个单例保持状态。通过应用过滤器,我得到了一个阻塞门,当底层门被提升时允许通过:

const gate$ = new BehaviorSubject(true); // open at first
const openGate$ = gate$.pipe(
    filter(x => x === true),
    take(1)   // take only one event, then complete
);

// wait for the gate to open
openGate$.subscribe(() => {
    // do something
});

// close the gate:
gate$.next(false);

// and open it again
gate$.next(true);

通过使用BehaviourSubject,门被初始化并默认打开。