-
Notifications
You must be signed in to change notification settings - Fork 36
/
continueWith.ts
75 lines (61 loc) · 1.92 KB
/
continueWith.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
import Pipe from '../sink/Pipe'
import { run } from '../run'
import { withLocalTime } from './withLocalTime'
import { disposeOnce, tryDispose } from '@most/disposable'
import { Stream, Scheduler, Time, Disposable, Sink } from '@most/types'
export const continueWith = <A>(f: () => Stream<A>, stream: Stream<A>): Stream<A> =>
new ContinueWith(f, stream)
class ContinueWith<A> implements Stream<A> {
private readonly f: () => Stream<A>
private readonly source: Stream<A>
constructor(f: () => Stream<A>, source: Stream<A>) {
this.f = f
this.source = source
}
run(sink: Sink<A>, scheduler: Scheduler): Disposable {
return new ContinueWithSink(this.f, this.source, sink, scheduler)
}
}
class ContinueWithSink<A> extends Pipe<A, A> implements Sink<A>, Disposable {
private readonly f: () => Stream<A>;
private readonly scheduler: Scheduler;
private active: boolean;
private disposable: Disposable
constructor(f: () => Stream<A>, source: Stream<A>, sink: Sink<A>, scheduler: Scheduler) {
super(sink)
this.f = f
this.scheduler = scheduler
this.active = true
this.disposable = disposeOnce(source.run(this, scheduler))
}
event(t: Time, x: A): void {
if (!this.active) {
return
}
this.sink.event(t, x)
}
end(t: Time): void {
if (!this.active) {
return
}
tryDispose(t, this.disposable, this.sink)
this.startNext(t, this.sink)
}
private startNext(t: Time, sink: Sink<A>): void {
try {
this.disposable = this.continue(this.f, t, sink)
} catch (e) {
sink.error(t, e)
}
}
private continue(f: () => Stream<A>, t: Time, sink: Sink<A>): Disposable {
return run(sink, this.scheduler, withLocalTime(t, f()))
}
dispose(): void {
this.active = false
return this.disposable.dispose()
}
}