| 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293 |
1x
11x
11x
1x
11x
11x
11x
11x
11x
11x
11x
11x
11x
1x
1x
46x
46x
1x
2x
2x
2x
1x
6x
5x
6x
15x
15x
15x
13x
2x
15x
5x
15x
12x
15x
6x
15x
15x
2x
2x
2x
1x
1x
2x
15x
15x
1x
3x
3x
3x
3x
1x
54x
54x
65x
65x
65x
65x
53x
53x
1x
1x
8x
8x
8x
8x
2x
8x
8x
8x
1x
1x
2x
2x
2x
15x
2x
21x
21x
13x
| /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export type NextFn<T> = (value: T) => void;
export type ErrorFn = (error: Error) => void;
export type CompleteFn = () => void;
export interface Observer<V, E> {
// Called once for each value in a stream of values.
next(value: V | null): any;
// A stream terminates by a single call to EITHER error() or complete().
error(error: E): any;
// No events will be sent to next() once complete() is called.
complete(): any;
}
// Allow for any of the Observer methods to be undefined.
export interface PartialObserver<T> {
next?: NextFn<T>;
error?: ErrorFn;
complete?: CompleteFn;
}
// TODO: Support also Unsubscribe.unsubscribe?
export type Unsubscribe = () => void;
/**
* The Subscribe interface has two forms - passing the inline function
* callbacks, or a object interface with callback properties.
*/
export interface Subscribe<T> {
(next?: NextFn<T>, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;
(observer: PartialObserver<T>): Unsubscribe;
}
export interface Observable<T> {
// Subscribe method
subscribe: Subscribe<T>;
}
export type Executor<T> = (observer: Observer<T, Error>) => void;
/**
* Helper to make a Subscribe function (just like Promise helps make a
* Thenable).
*
* @param executor Function which can make calls to a single Observer
* as a proxy.
* @param onNoObservers Callback when count of Observers goes to zero.
*/
export function createSubscribe<T>(
executor: Executor<T>,
onNoObservers?: Executor<T>
): Subscribe<T> {
let proxy = new ObserverProxy<T>(executor, onNoObservers);
return proxy.subscribe.bind(proxy);
}
/**
* Implement fan-out for any number of Observers attached via a subscribe
* function.
*/
class ObserverProxy<T> implements Observer<T, Error> {
private observers: Array<Observer<T, Error>> | undefined = [];
private unsubscribes: Unsubscribe[] = [];
private onNoObservers: Executor<T> | undefined;
private observerCount = 0;
// Micro-task scheduling by calling task.then().
private task = Promise.resolve();
private finalized = false;
private finalError: Error;
/**
* @param executor Function which can make calls to a single Observer
* as a proxy.
* @param onNoObservers Callback when count of Observers goes to zero.
*/
constructor(executor: Executor<T>, onNoObservers?: Executor<T>) {
this.onNoObservers = onNoObservers;
// Call the executor asynchronously so subscribers that are called
// synchronously after the creation of the subscribe function
// can still receive the very first value generated in the executor.
this.task
.then(() => {
executor(this);
})
.catch(e => {
this.error(e);
});
}
next(value: T) {
this.forEachObserver((observer: Observer<T, Error>) => {
observer.next(value);
});
}
error(error: Error) {
this.forEachObserver((observer: Observer<T, Error>) => {
observer.error(error);
});
this.close(error);
}
complete() {
this.forEachObserver((observer: Observer<T, Error>) => {
observer.complete();
});
this.close();
}
/**
* Subscribe function that can be used to add an Observer to the fan-out list.
*
* - We require that no event is sent to a subscriber sychronously to their
* call to subscribe().
*/
subscribe(
nextOrObserver: PartialObserver<T> | Function,
error?: ErrorFn,
complete?: CompleteFn
): Unsubscribe {
let observer: Observer<T, Error>;
Iif (
nextOrObserver === undefined &&
error === undefined &&
complete === undefined
) {
throw new Error('Missing Observer.');
}
// Assemble an Observer object when passed as callback functions.
if (implementsAnyMethods(nextOrObserver, ['next', 'error', 'complete'])) {
observer = nextOrObserver as Observer<T, Error>;
} else {
observer = {
next: (nextOrObserver as any) as NextFn<T>,
error: error,
complete: complete
} as Observer<T, Error>;
}
if (observer.next === undefined) {
observer.next = noop as NextFn<T>;
}
if (observer.error === undefined) {
observer.error = noop as ErrorFn;
}
if (observer.complete === undefined) {
observer.complete = noop as CompleteFn;
}
let unsub = this.unsubscribeOne.bind(this, this.observers!.length);
// Attempt to subscribe to a terminated Observable - we
// just respond to the Observer with the final error or complete
// event.
if (this.finalized) {
this.task.then(() => {
try {
if (this.finalError) {
observer.error(this.finalError);
} else {
observer.complete();
}
} catch (e) {
// nothing
}
return;
});
}
this.observers!.push(observer as Observer<T, Error>);
return unsub;
}
// Unsubscribe is synchronous - we guarantee that no events are sent to
// any unsubscribed Observer.
private unsubscribeOne(i: number) {
Iif (this.observers === undefined || this.observers[i] === undefined) {
return;
}
delete this.observers[i];
this.observerCount -= 1;
Iif (this.observerCount === 0 && this.onNoObservers !== undefined) {
this.onNoObservers(this);
}
}
private forEachObserver(fn: (observer: Observer<T, Error>) => void): void {
Iif (this.finalized) {
// Already closed by previous event....just eat the additional values.
return;
}
// Since sendOne calls asynchronously - there is no chance that
// this.observers will become undefined.
for (let i = 0; i < this.observers!.length; i++) {
this.sendOne(i, fn);
}
}
// Call the Observer via one of it's callback function. We are careful to
// confirm that the observe has not been unsubscribed since this asynchronous
// function had been queued.
private sendOne(i: number, fn: (observer: Observer<T, Error>) => void): void {
// Execute the callback asynchronously
this.task.then(() => {
if (this.observers !== undefined && this.observers[i] !== undefined) {
try {
fn(this.observers[i]);
} catch (e) {
// Ignore exceptions raised in Observers or missing methods of an
// Observer.
// Log error to console. b/31404806
Eif (typeof console !== 'undefined' && console.error) {
console.error(e);
}
}
}
});
}
private close(err?: Error): void {
Iif (this.finalized) {
return;
}
this.finalized = true;
if (err !== undefined) {
this.finalError = err;
}
// Proxy is no longer needed - garbage collect references
this.task.then(() => {
this.observers = undefined;
this.onNoObservers = undefined;
});
}
}
/** Turn synchronous function into one called asynchronously. */
export function async(fn: Function, onError?: ErrorFn): Function {
return (...args: any[]) => {
Promise.resolve(true)
.then(() => {
fn(...args);
})
.catch((error: Error) => {
if (onError) {
onError(error);
}
});
};
}
/**
* Return true if the object passed in implements any of the named methods.
*/
function implementsAnyMethods(obj: any, methods: string[]): boolean {
if (typeof obj !== 'object' || obj === null) {
return false;
}
for (let method of methods) {
if (method in obj && typeof obj[method] === 'function') {
return true;
}
}
return false;
}
function noop(): void {
// do nothing
}
|