How can I make sure that values are emitted conditionally from an observable? Specifically, in my scenario, subscribers of the .asObservable()
function should only receive a value after the CurrentUser
has been initialized.
export class CurrentUser {
private currentUser$: Observable<CurrentUser>;
private currentUserBehaviorSubject: BehaviorSubject<CurrentUser>;
public name: string = "";
constructor() {
this.currentUserBehaviorSubject = new BehaviorSubject(this);
this.currentUser$ = this.currentUserBehaviorSubject.asObservable();
}
public asObservable(): Observable<CurrentUser> {
//
if(user.name.length > 0){
return this.currentUser$;
}
else {
// ?????
}
}
public initialize(string name){
this.name = name;
this.currentUserBehaviorSubject.next(this);
}
}
export class SampleComponent {
constructor(
currentUser: CurrentUser
) {
currentUser.asObservable().subscribe(
(u: CurrentUser) => {
// i only want an INITIALIZED user here
},
error => {},
() => { }
);
}
}