| 1 |
import { OperatorFunction } from '../types'; |
| 2 |
import { operate } from '../util/lift'; |
| 3 |
import { createOperatorSubscriber } from './OperatorSubscriber'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Emits a given value if the source Observable completes without emitting any |
| 7 |
* `next` value, otherwise mirrors the source Observable. |
| 8 |
* |
| 9 |
* <span class="informal">If the source Observable turns out to be empty, then |
| 10 |
* this operator will emit a default value.</span> |
| 11 |
* |
| 12 |
*  |
| 13 |
* |
| 14 |
* `defaultIfEmpty` emits the values emitted by the source Observable or a |
| 15 |
* specified default value if the source Observable is empty (completes without |
| 16 |
* having emitted any `next` value). |
| 17 |
* |
| 18 |
* ## Example |
| 19 |
* |
| 20 |
* If no clicks happen in 5 seconds, then emit 'no clicks' |
| 21 |
* |
| 22 |
* ```ts |
| 23 |
* import { fromEvent, takeUntil, interval, defaultIfEmpty } from 'rxjs'; |
| 24 |
* |
| 25 |
* const clicks = fromEvent(document, 'click'); |
| 26 |
* const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000))); |
| 27 |
* const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks')); |
| 28 |
* result.subscribe(x => console.log(x)); |
| 29 |
* ``` |
| 30 |
* |
| 31 |
* @see {@link empty} |
| 32 |
* @see {@link last} |
| 33 |
* |
| 34 |
* @param defaultValue The default value used if the source |
| 35 |
* Observable is empty. |
| 36 |
* @return A function that returns an Observable that emits either the |
| 37 |
* specified `defaultValue` if the source Observable emits no items, or the |
| 38 |
* values emitted by the source Observable. |
| 39 |
*/ |
| 40 |
export function defaultIfEmpty<T, R>(defaultValue: R): OperatorFunction<T, T | R> { |
| 41 |
return operate((source, subscriber) => { |
| 42 |
let hasValue = false; |
| 43 |
source.subscribe( |
| 44 |
createOperatorSubscriber( |
| 45 |
subscriber, |
| 46 |
(value) => { |
| 47 |
hasValue = true; |
| 48 |
subscriber.next(value); |
| 49 |
}, |
| 50 |
() => { |
| 51 |
if (!hasValue) { |
| 52 |
subscriber.next(defaultValue!); |
| 53 |
} |
| 54 |
subscriber.complete(); |
| 55 |
} |
| 56 |
) |
| 57 |
); |
| 58 |
}); |
| 59 |
} |