-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interval.swift
42 lines (41 loc) · 1.03 KB
/
Interval.swift
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 Dispatch
import func Foundation.usleep
public func interval(
_ duration: DispatchTimeInterval,
on queue: DispatchQueue = DispatchQueue(label: DOMAIN("interval"))
) -> Producer<Int> {
return { sink in
let lock = RecursiveLock(label: DOMAIN("interval"))
var didReceiveCompletion: Bool = false
var i: Int = 0
sink(.start({ payload in
lock.withLock {
switch payload {
// NestedStartsNotAllowed From A Producer Perspective
case .start: break
case let .next(element):
if let element = element as? Int {
i = element
}
case .completed:
didReceiveCompletion = true
}
}
}))
func asyncRepeating() {
queue.asyncAfter(deadline: .now() + duration) {
usleep(1)
lock.withLock {
if !didReceiveCompletion {
sink(.next(i));
i += 1;
asyncRepeating()
} else {
sink(.completed(.finished))
}
}
}
}
asyncRepeating()
}
}