| 1 |
import { EmptyError } from '../util/EmptyError'; |
| 2 |
import { MonoTypeOperatorFunction } from '../types'; |
| 3 |
import { operate } from '../util/lift'; |
| 4 |
import { createOperatorSubscriber } from './OperatorSubscriber'; |
| 5 |
|
| 6 |
/** |
| 7 |
* If the source observable completes without emitting a value, it will emit |
| 8 |
* an error. The error will be created at that time by the optional |
| 9 |
* `errorFactory` argument, otherwise, the error will be {@link EmptyError}. |
| 10 |
* |
| 11 |
*  |
| 12 |
* |
| 13 |
* ## Example |
| 14 |
* |
| 15 |
* Throw an error if the document wasn't clicked within 1 second |
| 16 |
* |
| 17 |
* ```ts |
| 18 |
* import { fromEvent, takeUntil, timer, throwIfEmpty } from 'rxjs'; |
| 19 |
* |
| 20 |
* const click$ = fromEvent(document, 'click'); |
| 21 |
* |
| 22 |
* click$.pipe( |
| 23 |
* takeUntil(timer(1000)), |
| 24 |
* throwIfEmpty(() => new Error('The document was not clicked within 1 second')) |
| 25 |
* ) |
| 26 |
* .subscribe({ |
| 27 |
* next() { |
| 28 |
* console.log('The document was clicked'); |
| 29 |
* }, |
| 30 |
* error(err) { |
| 31 |
* console.error(err.message); |
| 32 |
* } |
| 33 |
* }); |
| 34 |
* ``` |
| 35 |
* |
| 36 |
* @param errorFactory A factory function called to produce the |
| 37 |
* error to be thrown when the source observable completes without emitting a |
| 38 |
* value. |
| 39 |
* @return A function that returns an Observable that throws an error if the |
| 40 |
* source Observable completed without emitting. |
| 41 |
*/ |
| 42 |
export function throwIfEmpty<T>(errorFactory: () => any = defaultErrorFactory): MonoTypeOperatorFunction<T> { |
| 43 |
return operate((source, subscriber) => { |
| 44 |
let hasValue = false; |
| 45 |
source.subscribe( |
| 46 |
createOperatorSubscriber( |
| 47 |
subscriber, |
| 48 |
(value) => { |
| 49 |
hasValue = true; |
| 50 |
subscriber.next(value); |
| 51 |
}, |
| 52 |
() => (hasValue ? subscriber.complete() : subscriber.error(errorFactory())) |
| 53 |
) |
| 54 |
); |
| 55 |
}); |
| 56 |
} |
| 57 |
|
| 58 |
function defaultErrorFactory() { |
| 59 |
return new EmptyError(); |
| 60 |
} |