-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathswitchMap.js
48 lines (47 loc) · 1.34 KB
/
switchMap.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
43
44
45
46
47
48
const Rx = require('./index');
const GroupSubscription = require('./GroupSubscription');
/**
* Rx.Observable.prototype.switchMap = require('toy-rx/switchMap');
*/
module.exports = function switchMap(transformFn) {
const inObservable = this;
const outObservable = Rx.Observable.create(function subscribe(outObserver) {
let innerSubscription = new Rx.Subscription(() => {});
let active = 1;
const inObserver = {
next: (x) => {
try {
var inner = transformFn(x);
} catch (e) {
outObserver.error(e);
return;
}
const innerObserver = {
next: (y) => outObserver.next(y),
error: (e) => outObserver.error(e),
complete: () => {
if (--active <= 0) {
outObserver.complete();
}
},
}
innerSubscription.unsubscribe();
innerSubscription.unsubscribe = inner.subscribe(innerObserver).unsubscribe;
},
error: (e) => {
outObserver.error(e);
},
complete: () => {
if (--active <= 0) {
outObserver.complete();
}
}
};
const subscription = new GroupSubscription();
subscription.add(innerSubscription);
active++;
subscription.add(inObservable.subscribe(inObserver));
return subscription;
});
return outObservable;
}