Skip to content

Instantly share code, notes, and snippets.

@fatbobman
Created Dec 4, 2021
Embed
What would you like to do?
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