首页 > 解决方案 > RxJS 6 - 在管道中第一次使用时我需要取消订阅吗?

问题描述

给定以下代码

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

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

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

标签: javascriptrxjs

解决方案


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

如果你想确定你可以添加complete回调tap,看看它是否被调用(你也可以添加它subscribe):

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

推荐阅读