-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathAsyncPassthroughSubject.swift
More file actions
54 lines (43 loc) · 1.17 KB
/
AsyncPassthroughSubject.swift
File metadata and controls
54 lines (43 loc) · 1.17 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
import AppKit
import Foundation
public actor AsyncPassthroughSubject<Element> {
var tasks: [AsyncStream<Element>.Continuation] = []
deinit {
tasks.forEach { $0.finish() }
}
public init() {}
public func notifications() -> AsyncStream<Element> {
AsyncStream { [weak self] continuation in
let task = Task { [weak self] in
await self?.storeContinuation(continuation)
}
continuation.onTermination = { termination in
task.cancel()
}
}
}
nonisolated
public func send(_ element: Element) {
Task { await _send(element) }
}
func _send(_ element: Element) {
let tasks = tasks
for task in tasks {
task.yield(element)
}
}
func storeContinuation(_ continuation: AsyncStream<Element>.Continuation) {
tasks.append(continuation)
}
nonisolated
public func finish() {
Task { await _finish() }
}
func _finish() {
let tasks = self.tasks
self.tasks = []
for task in tasks {
task.finish()
}
}
}