how to use the iif function from the rxjs library in javascript

The iif operator from the rxjs library allows you to conditionally subscribe to one observable sequence or another based on a condition.

Here's an example of how to use it:

index.tsx
const { iif } = require('rxjs');
const { tap, mergeMap } = require('rxjs/operators');

const isEven = num => num % 2 === 0;

const source$ = iif(
  () => isEven(Math.floor(Math.random() * 10)), // condition
  of('Even number'), // observable to subscribe to if condition is true
  of('Odd number') // observable to subscribe to if condition is false
);

source$
  .pipe(
    mergeMap(val => of(`Original value: ${val}`)),
    tap(console.log)
  )
  .subscribe();
463 chars
18 lines

In this example, we're using iif to generate a random number between 0 and 9, and then checking if it's even. If it is, we subscribe to an observable that emits the string 'Even number', otherwise we subscribe to an observable that emits the string 'Odd number'.

We then use mergeMap and tap operators to log the emitted values to the console.

Note that iif takes three arguments: the condition (a function that returns a boolean value), the observable to subscribe to if the condition is true, and the observable to subscribe to if the condition is false.

gistlibby LogSnag