我只想一次处理来自Observable的数据,但就我所知,我仍然必须取消订阅以防止内存泄漏。
最聪明的方法是什么?
通过使用pipe(take(1))或pipe(first()),我已经将订阅限制为一个事件,但是我仍然有一个开放的订阅,该订阅在第一次执行后是不必要的,还是会自动取消订阅? >
private user: Observable<User>;
constructor(private afAuth: AngularFireAuth, private afStore: AngularFirestore) {
this.user = this.afAuth.authState.pipe(
switchMap((user: firebase.User) => {
if (user) {
return this.afStore.doc<User>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
})
);
}
private someFunction(): void {
...
this.user.subscribe((user: User) => { // or this.user.pipe(first()).subscribe
console.log(user);
});
...
// maybe unsubscribe here, but what if we unsubscribe before executing code atleast once
}
如果我退订得太早,则有可能一次不获取数据。
答案 0 :(得分:0)
我要做的是创建订阅
private mySub: Subscription;
然后输入您的代码
this.mySub = this.user.subscribe((user: User) => { // or this.user.pipe(first()).subscribe
console.log(user);
});
然后在NgOnDestroy上
this.mySub.unsubscribe();
答案 1 :(得分:0)
感谢user184994!
使用take(1)或first()之后,订阅将自动取消订阅。
我像这样测试它:
private sub;
...
private someFunction(): void {
this.sub = this.user.subscribe((user: User) => {
console.log(user);
})
...
if (this.sub.closed) {
console.log("Subscription unsubscribed :)");
} else {
console.log("Subscription still alive :(");
}
}