diff --git a/Sources/FoundationExtensions/Concurrency/AsyncSequence.swift b/Sources/FoundationExtensions/Concurrency/AsyncSequence.swift new file mode 100644 index 0000000..061e0ee --- /dev/null +++ b/Sources/FoundationExtensions/Concurrency/AsyncSequence.swift @@ -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(_ kp: KeyPath) -> AsyncMapSequence { + map { $0[keyPath: kp] } + } +} diff --git a/Sources/FoundationExtensions/Promise/Promise.swift b/Sources/FoundationExtensions/Promise/Promise.swift index 2a7667a..83e3fd8 100644 --- a/Sources/FoundationExtensions/Promise/Promise.swift +++ b/Sources/FoundationExtensions/Promise/Promise.swift @@ -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(_:)`