I want to process data from an Observable just one single time, but then I still have to unsubscribe to prevent memory leaks as far as I understand.
What is the smartest way to do that?
By using pipe(take(1)) or pipe(first()) I already limited the subscription to one event but I still have an open Subscription which is unnecessary after the first execution or is it then automatically unsubscribed?
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
}
If I unsubscribe too early there is a potential risk of not getting data once.