-
Notifications
You must be signed in to change notification settings - Fork 0
/
observable.ts
49 lines (43 loc) · 1.13 KB
/
observable.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
44
45
46
47
48
49
import { Observer } from "./observer";
import { FilterFn, MapFn, NextMethod, SubscribeCallback, TapFn } from "./types";
export class Observable<T> {
private push: SubscribeCallback<T>;
constructor(push: SubscribeCallback<T>) {
this.push = push;
}
subscribe(observer: Observer<T>) {
const unsubscribe = this.push(observer);
return () => {
observer.complete();
unsubscribe();
}
}
map(mapFn: MapFn<T>): Observable<T> {
return new Observable(subscriber => {
return this.push(new Observer(
(x) => subscriber.next(mapFn(x)),
subscriber.error,
subscriber.complete,
));
});
}
filter(filterFn: FilterFn<T>): Observable<T> {
return new Observable(subscriber => {
return this.push(new Observer(
(x) => filterFn(x) ? subscriber.next(x) : null,
subscriber.error,
subscriber.complete,
));
});
}
tap(proc: TapFn<T>) {
return new Observable<T>(subscriber => {
return this.push(new Observer(x => {
proc(x);
subscriber.next(x);
},
subscriber.error,
subscriber.complete));
});
}
}