isEmpty.ts
2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OperatorFunction } from '../types';
/**
* Emits false if the input observable emits any values, or emits true if the
* input observable completes without emitting any values.
*
* <span class="informal">Tells whether any values are emitted by an observable</span>
*
* ![](isEmpty.png)
*
* `isEmpty` transforms an Observable that emits values into an Observable that
* emits a single boolean value representing whether or not any values were
* emitted by the source Observable. As soon as the source Observable emits a
* value, `isEmpty` will emit a `false` and complete. If the source Observable
* completes having not emitted anything, `isEmpty` will emit a `true` and
* complete.
*
* A similar effect could be achieved with {@link count}, but `isEmpty` can emit
* a `false` value sooner.
*
* ## Examples
*
* Emit `false` for a non-empty Observable
* ```javascript
* import { Subject } from 'rxjs';
* import { isEmpty } from 'rxjs/operators';
*
* const source = new Subject<string>();
* const result = source.pipe(isEmpty());
* source.subscribe(x => console.log(x));
* result.subscribe(x => console.log(x));
* source.next('a');
* source.next('b');
* source.next('c');
* source.complete();
*
* // Results in:
* // a
* // false
* // b
* // c
* ```
*
* Emit `true` for an empty Observable
* ```javascript
* import { EMPTY } from 'rxjs';
* import { isEmpty } from 'rxjs/operators';
*
* const result = EMPTY.pipe(isEmpty());
* result.subscribe(x => console.log(x));
* // Results in:
* // true
* ```
*
* @see {@link count}
* @see {@link EMPTY}
*
* @return {OperatorFunction<T, boolean>} An Observable of a boolean value indicating whether observable was empty or not
* @method isEmpty
* @owner Observable
*/
export function isEmpty<T>(): OperatorFunction<T, boolean> {
return (source: Observable<T>) => source.lift(new IsEmptyOperator());
}
class IsEmptyOperator implements Operator<any, boolean> {
call (observer: Subscriber<boolean>, source: any): any {
return source.subscribe(new IsEmptySubscriber(observer));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class IsEmptySubscriber extends Subscriber<any> {
constructor(destination: Subscriber<boolean>) {
super(destination);
}
private notifyComplete(isEmpty: boolean): void {
const destination = this.destination;
destination.next(isEmpty);
destination.complete();
}
protected _next(value: boolean) {
this.notifyComplete(false);
}
protected _complete() {
this.notifyComplete(true);
}
}