Skip to content

Instantly share code, notes, and snippets.

@fatbobman
Created December 4, 2021 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fatbobman/45ead2eac52c5f6f18f9f51cf294745f to your computer and use it in GitHub Desktop.
Save fatbobman/45ead2eac52c5f6f18f9f51cf294745f to your computer and use it in GitHub Desktop.
import Combine
import Foundation
public extension Publisher {
func task<T>(maxPublishers: Subscribers.Demand = .unlimited,
_ transform: @escaping (Output) async -> T) -> Publishers.FlatMap<Deferred<Future<T, Never>>, Self> {
flatMap(maxPublishers: maxPublishers) { value in
Deferred {
Future { promise in
Task {
let output = await transform(value)
promise(.success(output))
}
}
}
}
}
func task<T>(maxPublishers: Subscribers.Demand = .unlimited,
_ transform: @escaping (Output) async throws -> T) -> Publishers.FlatMap<Deferred<Future<T, Error>>, Self> {
flatMap(maxPublishers: maxPublishers) { value in
Deferred {
Future { promise in
Task {
do {
let output = try await transform(value)
promise(.success(output))
} catch {
promise(.failure(error))
}
}
}
}
}
}
func task<T>(maxPublishers: Subscribers.Demand = .unlimited,
_ transform: @escaping (Output) async throws -> T) -> Publishers.FlatMap<Deferred<Future<T, Error>>, Publishers.SetFailureType<Self, Error>> {
flatMap(maxPublishers: maxPublishers) { value in
Deferred {
Future { promise in
Task {
do {
let output = try await transform(value)
promise(.success(output))
} catch {
promise(.failure(error))
}
}
}
}
}
}
}
public extension Publisher {
func emptySink() -> AnyCancellable {
sink(receiveCompletion: { _ in }, receiveValue: { _ in })
}
}
public extension Publisher where Self.Failure == Never {
func emptySink() -> AnyCancellable {
sink(receiveValue: { _ in })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment