| 1 |
import { OperatorFunction } from '../types'; |
| 2 |
import { operate } from '../util/lift'; |
| 3 |
import { createOperatorSubscriber } from './OperatorSubscriber'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Emits `false` if the input Observable emits any values, or emits `true` if the |
| 7 |
* input Observable completes without emitting any values. |
| 8 |
* |
| 9 |
* <span class="informal">Tells whether any values are emitted by an Observable.</span> |
| 10 |
* |
| 11 |
*  |
| 12 |
* |
| 13 |
* `isEmpty` transforms an Observable that emits values into an Observable that |
| 14 |
* emits a single boolean value representing whether or not any values were |
| 15 |
* emitted by the source Observable. As soon as the source Observable emits a |
| 16 |
* value, `isEmpty` will emit a `false` and complete. If the source Observable |
| 17 |
* completes having not emitted anything, `isEmpty` will emit a `true` and |
| 18 |
* complete. |
| 19 |
* |
| 20 |
* A similar effect could be achieved with {@link count}, but `isEmpty` can emit |
| 21 |
* a `false` value sooner. |
| 22 |
* |
| 23 |
* ## Examples |
| 24 |
* |
| 25 |
* Emit `false` for a non-empty Observable |
| 26 |
* |
| 27 |
* ```ts |
| 28 |
* import { Subject, isEmpty } from 'rxjs'; |
| 29 |
* |
| 30 |
* const source = new Subject<string>(); |
| 31 |
* const result = source.pipe(isEmpty()); |
| 32 |
* |
| 33 |
* source.subscribe(x => console.log(x)); |
| 34 |
* result.subscribe(x => console.log(x)); |
| 35 |
* |
| 36 |
* source.next('a'); |
| 37 |
* source.next('b'); |
| 38 |
* source.next('c'); |
| 39 |
* source.complete(); |
| 40 |
* |
| 41 |
* // Outputs |
| 42 |
* // 'a' |
| 43 |
* // false |
| 44 |
* // 'b' |
| 45 |
* // 'c' |
| 46 |
* ``` |
| 47 |
* |
| 48 |
* Emit `true` for an empty Observable |
| 49 |
* |
| 50 |
* ```ts |
| 51 |
* import { EMPTY, isEmpty } from 'rxjs'; |
| 52 |
* |
| 53 |
* const result = EMPTY.pipe(isEmpty()); |
| 54 |
* result.subscribe(x => console.log(x)); |
| 55 |
* |
| 56 |
* // Outputs |
| 57 |
* // true |
| 58 |
* ``` |
| 59 |
* |
| 60 |
* @see {@link count} |
| 61 |
* @see {@link EMPTY} |
| 62 |
* |
| 63 |
* @return A function that returns an Observable that emits boolean value |
| 64 |
* indicating whether the source Observable was empty or not. |
| 65 |
*/ |
| 66 |
export function isEmpty<T>(): OperatorFunction<T, boolean> { |
| 67 |
return operate((source, subscriber) => { |
| 68 |
source.subscribe( |
| 69 |
createOperatorSubscriber( |
| 70 |
subscriber, |
| 71 |
() => { |
| 72 |
subscriber.next(false); |
| 73 |
subscriber.complete(); |
| 74 |
}, |
| 75 |
() => { |
| 76 |
subscriber.next(true); |
| 77 |
subscriber.complete(); |
| 78 |
} |
| 79 |
) |
| 80 |
); |
| 81 |
}); |
| 82 |
} |