Debian Codegraph @

node/rxjs/src/internal/observable/iif.ts

raw
1 import { Observable } from '../Observable';
2 import { defer } from './defer';
3 import { ObservableInput } from '../types';
4
5 /**
6 * Checks a boolean at subscription time, and chooses between one of two observable sources
7 *
8 * `iif` expects a function that returns a boolean (the `condition` function), and two sources,
9 * the `trueResult` and the `falseResult`, and returns an Observable.
10 *
11 * At the moment of subscription, the `condition` function is called. If the result is `true`, the
12 * subscription will be to the source passed as the `trueResult`, otherwise, the subscription will be
13 * to the source passed as the `falseResult`.
14 *
15 * If you need to check more than two options to choose between more than one observable, have a look at the {@link defer} creation method.
16 *
17 * ## Examples
18 *
19 * Change at runtime which Observable will be subscribed
20 *
21 * ```ts
22 * import { iif, of } from 'rxjs';
23 *
24 * let subscribeToFirst;
25 * const firstOrSecond = iif(
26 * () => subscribeToFirst,
27 * of('first'),
28 * of('second')
29 * );
30 *
31 * subscribeToFirst = true;
32 * firstOrSecond.subscribe(value => console.log(value));
33 *
34 * // Logs:
35 * // 'first'
36 *
37 * subscribeToFirst = false;
38 * firstOrSecond.subscribe(value => console.log(value));
39 *
40 * // Logs:
41 * // 'second'
42 * ```
43 *
44 * Control access to an Observable
45 *
46 * ```ts
47 * import { iif, of, EMPTY } from 'rxjs';
48 *
49 * let accessGranted;
50 * const observableIfYouHaveAccess = iif(
51 * () => accessGranted,
52 * of('It seems you have an access...'),
53 * EMPTY
54 * );
55 *
56 * accessGranted = true;
57 * observableIfYouHaveAccess.subscribe({
58 * next: value => console.log(value),
59 * complete: () => console.log('The end')
60 * });
61 *
62 * // Logs:
63 * // 'It seems you have an access...'
64 * // 'The end'
65 *
66 * accessGranted = false;
67 * observableIfYouHaveAccess.subscribe({
68 * next: value => console.log(value),
69 * complete: () => console.log('The end')
70 * });
71 *
72 * // Logs:
73 * // 'The end'
74 * ```
75 *
76 * @see {@link defer}
77 *
78 * @param condition Condition which Observable should be chosen.
79 * @param trueResult An Observable that will be subscribed if condition is true.
80 * @param falseResult An Observable that will be subscribed if condition is false.
81 * @return An observable that proxies to `trueResult` or `falseResult`, depending on the result of the `condition` function.
82 */
83 export function iif<T, F>(condition: () => boolean, trueResult: ObservableInput<T>, falseResult: ObservableInput<F>): Observable<T | F> {
84 return defer(() => (condition() ? trueResult : falseResult));
85 }