簡體   English   中英

RxJS 6 - 在管道中首次使用時是否需要取消訂閱?

[英]RxJS 6 - Do I need to unsubscribe when using first in a pipe?

鑒於以下代碼

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

RxJS 5 和 RxJS 6 版本的first工作方式相同,因此您無需取消訂閱,因為它完成了鏈並因此觸發了處置處理程序。

如果您想確保可以將complete回調添加到您的tap並查看它是否被調用(您也可以將其添加到subscribe中):

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

當時間間隔發出第一個值時,訂閱 $ 將取消訂閱。 請注意,即使 AppComponent 被銷毀,subscription$ 也不會取消訂閱,直到間隔發出一個值。

所以最好確保在 ngOnDestroy 鈎子中取消所有內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM