-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathChannel.swift
55 lines (44 loc) · 1.45 KB
/
Channel.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
43
44
45
46
47
48
49
50
51
52
53
54
55
actor Channel<Success: Sendable, Failure: Error>: Sendable {
private var state = State<Success, Failure>()
}
extension Channel {
@discardableResult
func fulfill(_ value: Success) async -> Bool {
if await state.result == nil {
await state.setResult(result: value)
for waiters in await state.waiters {
waiters.resume(returning: value)
}
await state.removeAllWaiters()
return false
}
return true
}
@discardableResult
func fail(_ failure: Failure) async -> Bool {
if await state.failure == nil {
await state.setFailure(failure: failure)
for waiters in await state.waiters {
waiters.resume(throwing: failure)
}
await state.removeAllWaiters()
return false
}
return true
}
var value: Success {
get async throws {
try await withCheckedThrowingContinuation { continuation in
Task {
if let result = await state.result {
continuation.resume(returning: result)
} else if let failure = await self.state.failure {
continuation.resume(throwing: failure)
} else {
await state.appendWaiters(waiters: continuation)
}
}
}
}
}
}