自習(xí)室.30 使用 takeUntil 操作符管理 Angular 組件的訂閱
在上一篇文章中,有個(gè)知友評論說是要 takeUntil 來管理訂閱更加清晰明了,那我們就探探究竟。
在 Rxjs 中,可以使用 takeUntil 來控制另外一個(gè) Observable 對象數(shù)據(jù)的產(chǎn)生。使用 takeUntil,上游的數(shù)據(jù)直接轉(zhuǎn)手給下游,直到takeUntil的參數(shù)吐出一個(gè)數(shù)據(jù)或者完結(jié)。
就像一個(gè)水龍頭開關(guān),一開始是打開的狀態(tài),上游的數(shù)據(jù)一開始直接流到下游,只要 takeUntil 一旦觸發(fā)吐出數(shù)據(jù),水龍頭立刻關(guān)閉。
利用這點(diǎn),可以在訂閱時(shí)時(shí),在管道中添加 takeUntil,在組件銷毀時(shí)吐出數(shù)據(jù),這樣這些訂閱就會立刻關(guān)閉,也就達(dá)到回收內(nèi)存的作用。
改造之前:
export?class?ExampleComponent?implements?OnInit,?OnDestroy?{
??subscription1:?Subscription;
??subscription2:?Subscription;
??ngOnInit():?void?{
????this.subscription1?=?observable1.subscribe(...);
????this.subscription2?=?observable2.subscribe(...);
??}
??ngOnDestroy()?{
????this.subscription1.unsubscribe();
????this.subscription2.unsubscribe();
??}
}
改造之后:
export?class?ExampleComponent?implements?OnInit,?OnDestroy?{
??destroy$:?Subject<boolean>?=?new?Subject<boolean>();
??ngOnInit():?void?{
????observable1
??????.pipe(takeUntil(this.destroy$))
??????.subscribe(...);
????observable2
??????.pipe(takeUntil(this.destroy$))
??????.subscribe(...);
??}
??ngOnDestroy()?{
????this.destroy$.next(true);
????this.destroy$.unsubscribe();
??}
}
總結(jié)
對比下來,你會發(fā)現(xiàn)takeUntil操作符會清晰簡潔很多,你只需要把takeUntil(this.destroy$)加入到想要組件銷毀時(shí)停止訂閱的管道,即可統(tǒng)一管理,感謝這位知友提供的思路。
評論
圖片
表情
