Give BehaviorSubject initial value - value being an Observable

DRNR picture DRNR · Nov 21, 2017 · Viewed 9.4k times · Source

I know that I cannot give BehaviorSubject an Observable value, but I need a way to solve this issue. On app initialization I am fetching current user (if exists), and I need to give the BehaviorSubject that potential value. So my service code looks like this:

private user = new BehaviorSubject<User>(this.getUser());
public user$ = this.user.asObservable();

getUser(): User {
  // does obviously not work!
  return this.apiService.getUser()
    .map(data => {
      if(data) {
        return data;
      }
      // do something else
    })  
}

So is there some magical rxjs operator to solve this issue, or some other possibility?

Thanks in advance!

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Nov 21, 2017

I would do it like

private user = new BehaviorSubject<User>(null);
public user$ = this.user.asObservable();

constructor() {
  this.getUser();
}

getUser(): User {
  // does obviously not work!
  return this.apiService.getUser()
    .subscribe(data => {
      if(!!data) {
        this.user.next(data); // <<== added
      }
      // do something else
    })  
}