iif

function stable

Checks a boolean at subscription time, and chooses between one of two observable sources

iif<T, F>(condition: () => boolean, trueResult: ObservableInput<T>, falseResult: ObservableInput<F>): Observable<T | F>

Parameters

condition

Condition which Observable should be chosen.

trueResult

An Observable that will be subscribed if condition is true.

falseResult

An Observable that will be subscribed if condition is false.

Returns

Observable<T | F>: An observable that proxies to trueResult or falseResult, depending on the result of the condition function.

Description

iif excepts a function that returns a boolean (the condition function), and two sources, the trueResult and the falseResult, and returns an Observable.

At the moment of subscription, the condition function is called. If the result is true, the subscription will be to the source passed as the trueResult, otherwise, the subscription will be to the source passed as the falseResult.

If you need to check more than two options to choose between more than one observable, have a look at the defer creation method.

Examples

Change at runtime which Observable will be subscribed

import { iif, of } from 'rxjs';

let subscribeToFirst;
const firstOrSecond = iif(
  () => subscribeToFirst,
  of('first'),
  of('second'),
);

subscribeToFirst = true;
firstOrSecond.subscribe(value => console.log(value));

// Logs:
// "first"

subscribeToFirst = false;
firstOrSecond.subscribe(value => console.log(value));

// Logs:
// "second"

Control an access to an Observable

let accessGranted;
const observableIfYouHaveAccess = iif(
  () => accessGranted,
  of('It seems you have an access...'), // Note that only one Observable is passed to the operator.
);

accessGranted = true;
observableIfYouHaveAccess.subscribe(
  value => console.log(value),
  err => {},
  () => console.log('The end'),
);

// Logs:
// "It seems you have an access..."
// "The end"

accessGranted = false;
observableIfYouHaveAccess.subscribe(
  value => console.log(value),
  err => {},
  () => console.log('The end'),
);

// Logs:
// "The end"

See Also

© 2015–2021 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/index/function/iif