File tree Expand file tree Collapse file tree
Tool/Sources/AsyncPassthroughSubject Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11import AppKit
22import Foundation
33
4- /// It uses notification center to mimic the behavior of a passthrough subject.
54public actor AsyncPassthroughSubject < Element> {
6- let name : Notification . Name
75 var tasks : [ AsyncStream < Element > . Continuation ] = [ ]
86
97 deinit {
108 tasks. forEach { $0. finish ( ) }
119 }
1210
13- public init ( ) {
14- name = NSNotification . Name (
15- " AsyncPassthroughSubject- \( UUID ( ) . uuidString) - \( String ( describing: Element . self) ) "
16- )
17- }
11+ public init ( ) { }
1812
1913 public func notifications( ) -> AsyncStream < Element > {
20- AsyncStream { [ weak self, name ] continuation in
14+ AsyncStream { [ weak self] continuation in
2115 let task = Task { [ weak self] in
2216 await self ? . storeContinuation ( continuation)
23- let notifications = NotificationCenter . default. notifications ( named: name)
24- . compactMap {
25- $0. object as? Element
26- }
27- for await notification in notifications {
28- try Task . checkCancellation ( )
29- guard self != nil else {
30- continuation. finish ( )
31- return
32- }
33- continuation. yield ( notification)
34- }
3517 }
3618
3719 continuation. onTermination = { termination in
@@ -46,7 +28,10 @@ public actor AsyncPassthroughSubject<Element> {
4628 }
4729
4830 func _send( _ element: Element ) {
49- NotificationCenter . default. post ( name: name, object: element)
31+ let tasks = tasks
32+ for task in tasks {
33+ task. yield ( element)
34+ }
5035 }
5136
5237 func storeContinuation( _ continuation: AsyncStream < Element > . Continuation ) {
You can’t perform that action at this time.
0 commit comments