Learn RxJS
Search…
iif

signature: iif(condition: () => boolean, trueResult: SubscribableOrPromise = EMPTY, falseResult: SubscribableOrPromise = EMPTY): Observable

Subscribe to first or second observable based on a condition

Examples

Example 1: simple iif
1
// RxJS v6+
2
import { iif, of, interval } from 'rxjs';
3
import { mergeMap } from 'rxjs/operators';
4
5
const r$ = of('R');
6
const x$ = of('X');
7
8
interval(1000)
9
.pipe(mergeMap(v => iif(() => v % 4 === 0, r$, x$)))
10
.subscribe(console.log);
11
12
// output: R, X, X, X, R, X, X, X, etc...
Copied!
Example 2: iif with mouse moves
1
// RxJS v6+
2
import { fromEvent, iif, of } from 'rxjs';
3
import { mergeMap, map, throttleTime, filter } from 'rxjs/operators';
4
5
const r$ = of(`I'm saying R!!`);
6
const x$ = of(`X's always win!!`);
7
8
fromEvent(document, 'mousemove')
9
.pipe(
10
throttleTime(50),
11
filter((move: MouseEvent) => move.clientY < 210),
12
map((move: MouseEvent) => move.clientY),
13
mergeMap(yCoord => iif(() => yCoord < 110, r$, x$))
14
)
15
.subscribe(console.log);
Copied!
Example 3: iif with default
1
// RxJS v6+
2
import { fromEvent, iif, of, interval, pipe } from 'rxjs';
3
import { mergeMap } from 'rxjs/operators';
4
5
interval(1000)
6
.pipe(
7
mergeMap(v =>
8
iif(
9
() => !!(v % 2),
10
of(v)
11
// if not supplied defaults to EMPTY
12
)
13
)
14
// output: 1,3,5...
15
)
16
.subscribe(console.log);
Copied!

Additional Resources

  • iif 📰 - Official docs
Last modified 2yr ago