Skip to content

Commit

Permalink
Merge pull request #40 from allaboutapps/sharedAsyncChannel
Browse files Browse the repository at this point in the history
SharedAsyncChannel
  • Loading branch information
aaa-developer authored Jan 14, 2025
2 parents 2298fc5 + 1fcadde commit 761e067
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
48 changes: 48 additions & 0 deletions Sources/Toolbox/Utilities/SharedAsyncChannel.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#if canImport(AsyncAlgorithms)
import AsyncAlgorithms
import Foundation

public final class SharedAsyncChannel<Element: Sendable>: AsyncSequence, @unchecked Sendable {
public typealias Element = Element
public typealias AsyncIterator = Iterator
private let lock = NSLock()
private var storage = [UUID: AsyncChannel<Element>]()

public init() {}

public func send(_ element: Element) async {
for channel in storage.values {
await channel.send(element)
}
}

public func makeAsyncIterator() -> Iterator {
let channel = AsyncChannel<Element>()
let id = UUID()
lock.lock()
storage[id] = channel
lock.unlock()
return Iterator(innerIterator: channel.makeAsyncIterator(), parent: self, id: id)
}

private func gotCancelled(id: UUID) {
lock.lock()
storage[id] = nil
lock.unlock()
}

public struct Iterator: AsyncIteratorProtocol {
var innerIterator: AsyncChannel<Element>.AsyncIterator
let parent: SharedAsyncChannel<Element>
let id: UUID

public mutating func next() async -> Element? {
return await withTaskCancellationHandler {
await innerIterator.next()
} onCancel: { [parent, id] in
parent.gotCancelled(id: id)
}
}
}
}
#endif
2 changes: 1 addition & 1 deletion Tests/ToolboxTests/TabBarCoordinatorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ final class TabBarCoordinatorTests: XCTestCase {

// Switch to the main actor context.
await MainActor.run {
let tabBarCoordinator = TabBarCoordinator()
let tabBarCoordinator = TabBarCoordinator(tabBarController: UITabBarController())

// Test your coordinator instance here, e.g.:
XCTAssertNotNil(tabBarCoordinator)
Expand Down

0 comments on commit 761e067

Please sign in to comment.