Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A future publisher backed by a passthrough subject.
// Publishers+Future.swift
// Created by Honghao Zhang on 9/21/20.
public extension Publishers {
/// A deferred future backed by a passthrough subject.
/// Note: This is because Future can create a memory leak.
static func future<Output, Failure: Error>(_ attemptToFulfill: @escaping (@escaping (Result<Output, Failure>) -> Void) -> Void) -> AnyPublisher<Output, Failure> {
Deferred<PassthroughSubject<Output, Failure>> {
let subject = PassthroughSubject<Output, Failure>()
attemptToFulfill { result in
switch result {
case .success(let value):
subject.send(completion: .finished)
case .failure(let error):
subject.send(completion: .failure(error))
return subject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment