Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / rxjs / src / internal / operators / throwIfEmpty.ts
1 import { EmptyError } from '../util/EmptyError';
2 import { Observable } from '../Observable';
3 import { Operator } from '../Operator';
4 import { Subscriber } from '../Subscriber';
5 import { TeardownLogic, MonoTypeOperatorFunction } from '../types';
6
7 /**
8  * If the source observable completes without emitting a value, it will emit
9  * an error. The error will be created at that time by the optional
10  * `errorFactory` argument, otherwise, the error will be {@link EmptyError}.
11  *
12  * ![](throwIfEmpty.png)
13  *
14  * ## Example
15  * ```ts
16  * import { fromEvent, timer } from 'rxjs';
17  * import { throwIfEmpty, takeUntil } from 'rxjs/operators';
18  *
19  * const click$ = fromEvent(document, 'click');
20  *
21  * click$.pipe(
22  *   takeUntil(timer(1000)),
23  *   throwIfEmpty(
24  *     () => new Error('the document was not clicked within 1 second')
25  *   ),
26  * )
27  * .subscribe({
28  *   next() { console.log('The button was clicked'); },
29  *   error(err) { console.error(err); }
30  * });
31  * ```
32  *
33  * @param errorFactory A factory function called to produce the
34  * error to be thrown when the source observable completes without emitting a
35  * value.
36  */
37 export function throwIfEmpty <T>(errorFactory: (() => any) = defaultErrorFactory): MonoTypeOperatorFunction<T> {
38   return (source: Observable<T>) => {
39     return source.lift(new ThrowIfEmptyOperator(errorFactory));
40   };
41 }
42
43 class ThrowIfEmptyOperator<T> implements Operator<T, T> {
44   constructor(private errorFactory: () => any) {
45   }
46
47   call(subscriber: Subscriber<T>, source: any): TeardownLogic {
48     return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));
49   }
50 }
51
52 class ThrowIfEmptySubscriber<T> extends Subscriber<T> {
53   private hasValue: boolean = false;
54
55   constructor(destination: Subscriber<T>, private errorFactory: () => any) {
56     super(destination);
57   }
58
59   protected _next(value: T): void {
60     this.hasValue = true;
61     this.destination.next(value);
62   }
63
64   protected _complete() {
65     if (!this.hasValue) {
66       let err: any;
67       try {
68         err = this.errorFactory();
69       } catch (e) {
70         err = e;
71       }
72       this.destination.error(err);
73     } else {
74         return this.destination.complete();
75     }
76   }
77 }
78
79 function defaultErrorFactory() {
80   return new EmptyError();
81 }