Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Sources/ConcurrencyExtras/AsyncStream.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import Foundation

extension AsyncStream {
/// Produces an `AsyncStream` from an `AsyncSequence` by consuming the sequence till it
/// terminates, ignoring any failure.
Expand Down Expand Up @@ -51,10 +53,13 @@ extension AsyncStream {
///
/// - Parameter sequence: An async sequence.
public init<S: AsyncSequence>(_ sequence: S) where S.Element == Element {
let lock = NSLock()
var iterator: S.AsyncIterator?
self.init {
if iterator == nil {
iterator = sequence.makeAsyncIterator()
lock.withLock {
if iterator == nil {
iterator = sequence.makeAsyncIterator()
}
}
return try? await iterator?.next()
}
Expand Down
9 changes: 7 additions & 2 deletions Sources/ConcurrencyExtras/AsyncThrowingStream.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import Foundation

extension AsyncThrowingStream where Failure == Error {
/// Produces an `AsyncThrowingStream` from an `AsyncSequence` by consuming the sequence till it
/// terminates, rethrowing any failure.
///
/// - Parameter sequence: An async sequence.
public init<S: AsyncSequence>(_ sequence: S) where S.Element == Element {
let lock = NSLock()
var iterator: S.AsyncIterator?
self.init {
if iterator == nil {
iterator = sequence.makeAsyncIterator()
lock.withLock {
if iterator == nil {
iterator = sequence.makeAsyncIterator()
}
}
return try await iterator?.next()
}
Expand Down
11 changes: 11 additions & 0 deletions Sources/ConcurrencyExtras/Internal/Locking.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Foundation

#if !(os(iOS) || os(macOS) || os(tvOS) || os(watchOS))
extension NSLock {
func withLock<R>(_ body: () throws -> R) rethrows -> R {
self.lock()
defer { self.unlock() }
return try body()
}
}
#endif