angulartypescriptrxjs7

Using nested rxjs iif operators not working as expected


The following is just a section of the code, but should be enough.

In this case the allocateEquipment gets called when eq is an empty array and dryRun is true.

...

tap(a => console.log(a)), // logs [] length:0
concatMap(eq =>
  iif(() => Array.isArray(eq) && eq.length > 0,
    iif(() => dryRun, of(eq), this.allocatEquipment(of(eq)))
    , EMPTY)
)

Expected to return EMPTY


Solution

  • iif is a tricky operator, see a very good answer here. Long story short:

    The role of iif is not to execute one path over the other, but to subscribe to one Observable or the other. That said, it will execute any and all code paths required to get each Observable.

    In your case, I would try to rework it with ternary operator

    concatMap(eq =>
      iif(() => Array.isArray(eq) && eq.length > 0,
        dryRun ? of(eq) : this.allocatEquipment(of(eq)),
        EMPTY)
    );
    

    It will still subscribe to the second option, but this time dryRun condition should prevent it from executing this.allocatEquipment(of(eq).