chandradot99
chandradot99

Reputation: 3866

How to call second observable only if first Observable returns null

suppose i have two methods which returns an observable

method1(): Observable<any> {
  returns data or null;
}

method2(): Observable<any> {
 always returns data;
}

Now i call method1 first, if this returns some data, then don't call method2, otherwise call method2.

I can do something like this,

this.method1().subscribe(data => {
  if(data == null)
    this.method2().subscribe(data => {
      return data;
    })
  else {
    return data;
  }
})

But i think, this is not the proper way to handle this situation. It can be handled very easily with Observable Operators which i am missing.

Upvotes: 3

Views: 1434

Answers (1)

slaesh
slaesh

Reputation: 16917

Don't subscribe, use flatMap instead.

export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }

  ngOnInit() {
    this.method3().subscribe(data => console.log('data', data));
  }

  method1(): Observable<any> {
    return Observable.of(null);
    //return Observable.of({ not: null });
  }

  method2(): Observable<any> {
    return Observable.of({ any: 'data' });
  }

  method3(): Observable<any> {
    return this.method1().flatMap(data => {
      console.log('m1', data);

      if (data) return Observable.of(data);
      return this.method2();
    });
  }
}

live-demo: https://plnkr.co/edit/4G8Yr6OgpRqifWNfLmQN?p=preview

Upvotes: 3

Related Questions