Home > database >  RXJS conditionally call observable
RXJS conditionally call observable

Time:04-28

  const observable$ = iif(() => this.shippingTabModified,
      //Shipping Tab Modified True
      of(this.updateShippingInfo())
        .pipe(),
      //IF Shipping Tab Not Modified    
      of(this.shippingInfoService.getShipmentInfoByCardIdObservable(this.data.CardId))
        .pipe()
    )

    observable$.subscribe();

From above code i want to achieve following scenario

if(foo === true)
{
  updatemethod()
}
// if foo is true and update method is executed we need to wait until update method is finished then go to second method

// If foo is false we can call second method without waiting
secondmethod();

But from rxjs code which i wrote above, it always go to update method it is not considering the value of this.shippingTabModified

CodePudding user response:

You can leverage on the concat function and do something like this

const observables$ = condition ? [obs$1, obs$2] : [obs$2];

concat(...observables$).subscribe();

Cheers

CodePudding user response:

Why not just use


const obs$ = this.shippingTabModified ? 
  of(this.updateShippingInfo()) : 
  this.shippingInfoService.getShipmentInfoByCardIdObservable(this.data.CardId);

obs$.subscribe();

EDIT

Calling on condition :

const obs$ = of(this.updateShippingInfo()).pipe(
  switchMap(res => this.shippingTabModified ?
    of(res) :
    this
      .shippingInfoService
      .getShipmentInfoByCardIdObservable(this.data.CardId)
)
  • Related