Skip to content

Commit

Permalink
add concurrency bridge to Promise. (#50)
Browse files Browse the repository at this point in the history
Co-authored-by: Oguz Yuksel <oguz.yueksel@teufel.de>
  • Loading branch information
OguzYuuksel and Oguz Yuksel authored Jul 25, 2023
1 parent 6b9bd39 commit fe3a226
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Sources/FoundationExtensions/Concurrency/AsyncSequence.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright © 2023 Lautsprecher Teufel GmbH. All rights reserved.

import _Concurrency

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension AsyncSequence {

/// Returns a new asynchronous sequence that transforms the elements of the sequence using a key path.
///
/// This method works as a shortcut for the `map` function, specifically using a key path as the transform function. Each element of the sequence is transformed to the value at the specified key path of the element.
///
/// - Parameter kp: A key path that specifies which property value to map from each element in the sequence.
/// - Returns: A new asynchronous sequence that contains the transformed elements. Each element is the value at the specified key path of the corresponding element in the original sequence.
@inlinable
public func map<Value>(_ kp: KeyPath<Element, Value>) -> AsyncMapSequence<Self, Value> {
map { $0[keyPath: kp] }
}
}
26 changes: 26 additions & 0 deletions Sources/FoundationExtensions/Promise/Promise.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,32 @@ extension Publishers {
}
}

public init(_ asyncFunc: @escaping () async throws -> Success) where Failure == Error {
self.init { promise in
let task = Task {
do {
let result = try await asyncFunc()
promise(.success(result))
} catch {
promise(.failure(error))
}
}

return AnyCancellable { task.cancel() }
}
}

public init(_ asyncFunc: @escaping () async -> Success) where Failure == Never {
self.init { promise in
let task = Task {
let result = await asyncFunc()
promise(.success(result))
}

return AnyCancellable { task.cancel() }
}
}

/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
Expand Down

0 comments on commit fe3a226

Please sign in to comment.