【问题标题】:RxJS 6 - Do I need to unsubscribe when using first in a pipe?RxJS 6 - 在管道中第一次使用时我需要取消订阅吗?
【发布时间】:2018-11-10 18:07:52
【问题描述】:

给定以下代码

function triggerAction() {
    const asyncAction$ = of("value1");
    asyncAction$
        .clientLogin()
        .pipe(
            first(),
            tap(val => console.log(`Test: ${val}`)),
        )
        .subscribe();
}

我需要退订吗?以前,当 first 与修补运算符一起使用时,一旦发出第一个事件,它们就会自行取消订阅,但从文档中并不清楚管道运算符等效项是否相同。

https://www.learnrxjs.io/operators/filtering/first.html https://rxjs-dev.firebaseapp.com/api/operators/first

【问题讨论】:

    标签: javascript rxjs


    【解决方案1】:

    first 的 RxJS 5 和 RxJS 6 版本的工作方式相同,因此您无需取消订阅,因为它完成了链并因此触发了处置处理程序。

    如果您想确保可以将 complete 回调添加到您的 tap 并查看它是否被调用(您也可以将其添加到 subscribe):

    asyncAction$
        .clientLogin()
        .pipe(
            first(),
            tap({
                next: val => console.log(`Test: ${val}`),
                complete: () => console.log(`Complete`),
            }),
        )
        .subscribe();
    

    【讨论】:

      【解决方案2】:

      当间隔发出第一个值时,订阅$ 将取消订阅。 请注意,即使 AppComponent 被销毁,subscription$ 也不会取消订阅,直到间隔发出一个值。

      因此最好确保在 ngOnDestroy 挂钩中取消所有内容。

      【讨论】:

        猜你喜欢
        • 2018-09-15
        • 2020-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        • 1970-01-01
        • 2018-07-29
        相关资源
        最近更新 更多