@@ -39,21 +39,20 @@ export class PubSubAsyncIterator<T> implements AsyncIterator<T> {
39
39
this . pushQueue = [ ] ;
40
40
this . listening = true ;
41
41
this . eventsArray = typeof eventNames === 'string' ? [ eventNames ] : eventNames ;
42
- this . allSubscribed = this . subscribeAll ( ) ;
43
42
}
44
43
45
44
public async next ( ) {
46
- await this . allSubscribed ;
45
+ await this . subscribeAll ( ) ;
47
46
return this . listening ? this . pullValue ( ) : this . return ( ) ;
48
47
}
49
48
50
49
public async return ( ) {
51
- this . emptyQueue ( await this . allSubscribed ) ;
50
+ await this . emptyQueue ( ) ;
52
51
return { value : undefined , done : true } ;
53
52
}
54
53
55
54
public async throw ( error ) {
56
- this . emptyQueue ( await this . allSubscribed ) ;
55
+ await this . emptyQueue ( ) ;
57
56
return Promise . reject ( error ) ;
58
57
}
59
58
@@ -64,13 +63,13 @@ export class PubSubAsyncIterator<T> implements AsyncIterator<T> {
64
63
private pullQueue : Function [ ] ;
65
64
private pushQueue : any [ ] ;
66
65
private eventsArray : string [ ] ;
67
- private allSubscribed : Promise < number [ ] > ;
66
+ private subscriptionIds : Promise < number [ ] > | undefined ;
68
67
private listening : boolean ;
69
68
private pubsub : PubSubEngine ;
70
69
private options : Object ;
71
70
72
71
private async pushValue ( event ) {
73
- await this . allSubscribed ;
72
+ await this . subscribeAll ( ) ;
74
73
if ( this . pullQueue . length !== 0 ) {
75
74
this . pullQueue . shift ( ) ( { value : event , done : false } ) ;
76
75
} else {
@@ -88,20 +87,23 @@ export class PubSubAsyncIterator<T> implements AsyncIterator<T> {
88
87
} ) ;
89
88
}
90
89
91
- private emptyQueue ( subscriptionIds : number [ ] ) {
90
+ private async emptyQueue ( ) {
92
91
if ( this . listening ) {
93
92
this . listening = false ;
94
- this . unsubscribeAll ( subscriptionIds ) ;
93
+ if ( this . subscriptionIds ) this . unsubscribeAll ( await this . subscriptionIds ) ;
95
94
this . pullQueue . forEach ( resolve => resolve ( { value : undefined , done : true } ) ) ;
96
95
this . pullQueue . length = 0 ;
97
96
this . pushQueue . length = 0 ;
98
97
}
99
98
}
100
99
101
100
private subscribeAll ( ) {
102
- return Promise . all ( this . eventsArray . map (
103
- eventName => this . pubsub . subscribe ( eventName , this . pushValue . bind ( this ) , this . options ) ,
104
- ) ) ;
101
+ if ( ! this . subscriptionIds ) {
102
+ this . subscriptionIds = Promise . all ( this . eventsArray . map (
103
+ eventName => this . pubsub . subscribe ( eventName , this . pushValue . bind ( this ) , this . options ) ,
104
+ ) ) ;
105
+ }
106
+ return this . subscriptionIds
105
107
}
106
108
107
109
private unsubscribeAll ( subscriptionIds : number [ ] ) {
0 commit comments