-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathasyncobserverx.ts
More file actions
55 lines (46 loc) · 1.11 KB
/
asyncobserverx.ts
File metadata and controls
55 lines (46 loc) · 1.11 KB
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
import { AsyncObserver } from '../interfaces';
enum ObserverState {
Idle,
Busy,
Done,
}
export abstract class AsyncObserverX<T> implements AsyncObserver<T> {
private _state: ObserverState = ObserverState.Idle;
next(value: T) {
this._tryEnter();
try {
return this._next(value);
} finally {
this._state = ObserverState.Idle;
}
}
abstract _next(value: T): Promise<void>;
error(err: any) {
this._tryEnter();
try {
return this._error(err);
} finally {
this._state = ObserverState.Done;
}
}
abstract _error(err: any): Promise<void>;
complete() {
this._tryEnter();
try {
return this._complete();
} finally {
this._state = ObserverState.Done;
}
}
abstract _complete(): Promise<void>;
private _tryEnter() {
const old = this._state;
if (old === ObserverState.Idle) {
this._state = ObserverState.Busy;
} else if (old === ObserverState.Busy) {
throw new Error('Observer is already busy');
} else if (old === ObserverState.Done) {
throw new Error('Observer has already terminated');
}
}
}