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

To use the iif function from the rxjs library in typescript, you'll need to install RxJS via npm first:

index.ts
npm install rxjs
17 chars
2 lines

Afterwards, you can import and use the iif function like this:

index.ts
import { iif, of } from 'rxjs';
import { map } from 'rxjs/operators';

const condition = true;
const sub1 = of('A').pipe(
  map(val => 'Value: ' + val)
).subscribe(console.log);

const sub2 = iif(() => condition, sub1).subscribe(console.log);
243 chars
10 lines

In this example, we first import the iif and of functions from the rxjs library, as well as the map() function from the rxjs/operators module.

We then declare a condition variable with a boolean value of true, and create an observable sub1 that emits the string 'A', maps it to the string 'Value: A' using map(), and logs it to the console via console.log().

Finally, we create a second observable sub2 using iif(), which takes a condition function (in this case, a simple arrow function that returns the boolean condition variable), and two observables: sub1 and EMPTY (which is a built-in RxJS observable that emits no values and immediately completes). If the condition is true, iif() subscribes to and emits the values from sub1. If the condition is false, iif() subscribes to and emits the values from EMPTY.

We subscribe to sub2 using console.log() as the observer function, which will log 'Value: A' to the console if the condition is true, or immediately complete if the condition is false.

gistlibby LogSnag