-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathrxjs_utils.ts
43 lines (39 loc) · 1.05 KB
/
rxjs_utils.ts
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { Observable } from 'rxjs';
export class AbortError extends Error {}
export const toPromiseAbortable = <T>(
observable: Observable<T>,
signal?: AbortSignal
): Promise<T> =>
new Promise((resolve, reject) => {
if (signal && signal.aborted) {
reject(new AbortError('Aborted'));
return;
}
const listener = () => {
subscription.unsubscribe();
reject(new AbortError('Aborted'));
};
const cleanup = () => {
if (signal) {
signal.removeEventListener('abort', listener);
}
};
const subscription = observable.subscribe(
(data) => {
cleanup();
resolve(data);
},
(err) => {
cleanup();
reject(err);
}
);
if (signal) {
signal.addEventListener('abort', listener, { once: true });
}
});