Rushabh Joshi
Rushabh Joshi

Reputation: 233

Observable.if not working properly

I dont know guys but whats wrong with this?

this.auth.userAvailable(data.email)
    .flatMap(res => {
      return Observable.if(
        function () {
          return res.success;
        },
        Observable.fromPromise(this.auth.localStore('user_info', data)),
        Observable.throw(new Error('User exists'))
      )
    })
    .subscribe(res => {
      this.navCtrl.push(ServiceProviderBusinessInfoPage);
    }, err => {
      let error = err.json();
      this.alertCtrl.create({
        title: 'Error',
        message: error.message,
        buttons: ['OK']
      }).present();
    });

even if the res.success returns false everytime this.auth.localStore('user_info', data) gets fired, also subscribe success call is not getting fired

help me with this code, I am new for rxjs

Upvotes: 2

Views: 839

Answers (2)

Chris Tapay
Chris Tapay

Reputation: 1023

This has to do with how if works. This was reported here: https://github.com/ReactiveX/rxjs/issues/2768

And workaround placed here: https://github.com/ReactiveX/rxjs/issues/2768#issuecomment-317877914

So applying to your example, it would be:

this.auth.userAvailable(data.email)
    .switchMap(res => {
      return Observable.if(
        () => res.success,
        Observable.defer(() => Observable.fromPromise(this.auth.localStore('user_info', data))),
        Observable.throw(new Error('User exists'))
      )
    })
    .subscribe(res => {
...

Upvotes: 0

Olaf Horstmann
Olaf Horstmann

Reputation: 16882

In your case there is not really the need for an Observable.if, why not use a simple switchMap:

this.auth.userAvailable(data.email)
    .switchMap(res => {
      if (res.success) {
        return Observable.fromPromise(this.auth.localStore('user_info', data));
      } else {
        return Observable.throw(new Error('User exists'));
      }
    })
    .subscribe(res => {
      this.navCtrl.push(ServiceProviderBusinessInfoPage);
    }, err => {
      let error = err.json();
      this.alertCtrl.create({
        title: 'Error',
        message: error.message,
        buttons: ['OK']
      }).present();
    });

Upvotes: 2

Related Questions