I'm a bit confused about how to use takeWhile
.
Here's what I'm trying to achieve:
- Wait for the Observable
fireAuthUser$
to emit a value - Once it emits a value, perform some actions
- If
fireAuthUser$
doesn't emit a value, cancel when the component is destroyed
export class AuthService implements OnDestroy {
fireAuthUser: BehaviorSubject<firebase.User | undefined> = new BehaviorSubject<firebase.User | undefined>(undefined);
public readonly fireAuthUser$: Observable<firebase.User | undefined> = this.fireAuthUser.asObservable();
private subscription?: Subscription;
constructor(public fire: AngularFireAuth) {
this.subscription = this.fire.authState.subscribe((fireAuthUser) => {
if (fireAuthUser) {
this.fireAuthUser.next(fireAuthUser);
// ...
}
});
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
doSomeStuff(): void {
//do some stuff
}
}
export class Foo implements OnInit {
constructor(public auth: AuthService) { }
ngOnInit(): void {
this.auth.fireAuthUser$.pipe(takeWhile((fireAuthUser) => fireAuthUser === undefined)).subscribe({
complete: () => this.auth.doSomeStuff()
});
}
}
The code above seems to work, but there's a concern raised in this Stack Overflow post about using takeWhile and unsubscribing. The suggestion is to manually set a value on ngOnDestroy
, but doing so might erase the existing fireAuthUser
object. What should be done in this scenario?