1
- import { tap } from './tap' ;
2
1
import { EmptyError } from '../util/EmptyError' ;
3
- import { MonoTypeOperatorFunction } from '../types' ;
2
+ import { Observable } from '../Observable' ;
3
+ import { Operator } from '../Operator' ;
4
+ import { Subscriber } from '../Subscriber' ;
5
+ import { TeardownLogic , MonoTypeOperatorFunction } from '../types' ;
4
6
5
7
/**
6
8
* If the source observable completes without emitting a value, it will emit
@@ -24,24 +26,55 @@ import { MonoTypeOperatorFunction } from '../types';
24
26
* )
25
27
* .subscribe({
26
28
* next() { console.log('The button was clicked'); },
27
- * error(err) { console.error(err); },
29
+ * error(err) { console.error(err); }
28
30
* });
29
31
* ```
30
32
*
31
- * @param { Function } [ errorFactory] A factory function called to produce the
33
+ * @param errorFactory A factory function called to produce the
32
34
* error to be thrown when the source observable completes without emitting a
33
35
* value.
34
36
*/
35
- export const throwIfEmpty =
36
- < T > ( errorFactory : ( ( ) => any ) = defaultErrorFactory ) => tap < T > ( {
37
- hasValue : false ,
38
- next ( ) { this . hasValue = true ; } ,
39
- complete ( ) {
40
- if ( ! this . hasValue ) {
41
- throw errorFactory ( ) ;
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 ;
42
71
}
72
+ this . destination . error ( err ) ;
73
+ } else {
74
+ return this . destination . complete ( ) ;
43
75
}
44
- } as any ) ;
76
+ }
77
+ }
45
78
46
79
function defaultErrorFactory ( ) {
47
80
return new EmptyError ( ) ;
0 commit comments