Skip to content

Commit

Permalink
✨ Add new extensions for Combine+Concurrency
Browse files Browse the repository at this point in the history
  • Loading branch information
olejnjak committed Mar 14, 2024
1 parent 8eee630 commit 96fb573
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

## Next

- Add new helpers for Combine+Concurrency ([#147](https://github.com/AckeeCZ/ACKategories/pull/147), kudos to @olejnjak)

## 6.13.0
- Merge [iOS template lib](https://github.com/AckeeCZ/iOS-MVVM-ProjectTemplate) ([#143](https://github.com/AckeeCZ/ACKategories/pull/143), kudos to @olejnjak)
- add Networking module
Expand Down
40 changes: 36 additions & 4 deletions Sources/ACKategories/Combine+Concurrency.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import Combine

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Future where Failure == Error {
convenience init(operation: @escaping () async throws -> Output) {
public extension Future {
/// Run async operation as Publisher
/// - Parameter operation: Operation to be run
convenience init(operation: @escaping () async throws -> Output) where Failure == Error {
self.init { promise in
Task {
do {
Expand All @@ -13,11 +15,41 @@ public extension Future where Failure == Error {
}
}
}

/// Run async operation as Publisher
/// - Parameter operation: Operation to be run
convenience init(operation: @escaping () async -> Result<Output, Failure>) {
self.init { promise in
Task { promise(await operation()) }
}
}

/// Run async operation as Publisher
/// - Parameter operation: Operation to be run
convenience init(operation: @escaping () async -> Output) where Failure == Never {
self.init { promise in
Task { promise(.success(await operation())) }
}
}
}

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension AnyPublisher where Failure == Error {
init(operation: @escaping () async throws -> Output) {
public extension AnyPublisher {
/// Run async operation as Publisher
/// - Parameter operation: Operation to be run
init(operation: @escaping () async throws -> Output) where Failure == Error {
self = Future { try await operation() }.eraseToAnyPublisher()
}

/// Run async operation as Publisher
/// - Parameter operation: Operation to be run
init(operation: @escaping () async -> Result<Output, Failure>) {
self = Future { await operation() }.eraseToAnyPublisher()
}

/// Run async operation as Publisher
/// - Parameter operation: Operation to be run
init(operation: @escaping () async -> Output) where Failure == Never {
self = Future { await operation() }.eraseToAnyPublisher()
}
}

0 comments on commit 96fb573

Please sign in to comment.