RxJS的行为不符合预期

问题描述 投票:0回答:1

我正在使用RxJS 6制作一个Angular 8应用程序。我认为我对RxJS的使用相当不错,但今天我遇到了一些事情,让我认为我对它的工作方式有了根本性的误解。

我有以下的订阅。

this.nudgePauseConnectivity$.pipe(
    tap(() => console.log(1)),
    withLatestFrom(this.hotspotPausedState$()),
    tap(() => console.log(2)),
    filter(([nudgePause, connectionPaused]) => connectionPaused === enums.HotspotPausedStateEnum.FALSE),
    tap(() => console.log(3)),
    switchMapTo(this._store.pipe(select(this._hotspotSelectors.selectUsername))),
    tap(() => console.log(4)),
    switchMap(username =>
        this._cabinApiV2Service.subscriberService.getRemainingConnectivityAllowance(username)
    ),
    tap(() => console.log(5)),
    map(remainingConnectivityAllowance => SubscriberConnectivityAllowanceTransformer.transform(
        remainingConnectivityAllowance
    ))
).subscribe(() => {/* Do something */});

nudgePauseConnectivity$ 是一个主题,我用它来让观察对象的主体执行,就像这样。

pauseConnectivity() {
    this.nudgePauseConnectivity$.next({});
}

this._hotspotSelectors.selectUsername 是一个NgRx选择器 如果你还没有在一个observable中使用NgRx 从一个存储中返回值的话

我的问题是这样的。我以为这个表达式会执行 曾经 的每一个数值。this.nudgePauseConnectivity$. 我希望能在控制台看到。

1

2

3

4

5

然而,似乎即使 this.nudgePauseConnectivity$ 没有发出一个值,如果表达式的执行从 this._store.pipe(select(this._hotspotSelectors.selectUsername)) 发出一个值,所以我在控制台中看到这样的输出。

1

2

3

4

5

4

5

我彻底被这个问题搞糊涂了! 我不希望表达式在中间开始执行。我希望表达式只在if this.nudgePauseConnectivity$ 中的任何表达式的值,都会发出一个值。switchMap的或其他高阶可观察的运算符在链的后期。

我如何实现这个目标?

angular typescript rxjs
1个回答
2
投票

switchMap在第一次发射后并没有取消订阅。你应该这样做。我们通常会忘记这一点,因为大多数时候我们处理的是1个可观测的发射,比如http客户端。由于你有一个流,当你的应用程序的生活,而不是。

switchMapTo(this._store.pipe(select(this._hotspotSelectors.selectUsername))),

你可以这样做 中断所有的链子 nudgePauseConnectivity$ - 这将限制仅来自 switchMap 到单一排放,但将保持认购的 nudgePauseConnectivity$ active)。

switchMap(() => this._store.pipe(
 select(this._hotspotSelectors.selectUsername), 
 take(1)
)

或者只是把 take(1) 连带 switchMapTo 如果你想中断第一次排放后的所有排放(它将取消订阅的 nudgePauseConnectivity$ 后的第一次发射)。)

...
switchMapTo(this._store.pipe(select(this._hotspotSelectors.selectUsername))),
take(1),
...

值得看看你代码的其他部分,看看你是否正确地退订了表格 你正在使用的观测值(甚至是那些角形的观测值)。

© www.soinside.com 2019 - 2024. All rights reserved.