forked from benlesh/tc39-observable-proposal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
race.js
42 lines (34 loc) · 964 Bytes
/
race.js
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
import AbortController from "abort-controller";
import Observable from "../../Observable.js";
export default function race(sources) {
return new Observable(
(nextHandler, errorHandler, completeHandler, signal) => {
let winner;
const controllers = [];
sources.forEach(source => {
const controller = new AbortController();
signal.addEventListener("abort", () => controller.abort());
if (winner) {
controller.abort();
}
controllers.push(controller);
source.subscribe(
next => {
if (!winner) {
winner = source;
controllers.forEach(other => {
if (other !== controller) {
other.abort();
}
});
}
nextHandler(next);
},
errorHandler,
completeHandler,
controller.signal,
);
});
},
);
}