Skip to content

Instantly share code, notes, and snippets.

@honghaoz
Created September 22, 2020 03:42
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 honghaoz/a38f7679c2242659cc87d788b62f4643 to your computer and use it in GitHub Desktop.
Save honghaoz/a38f7679c2242659cc87d788b62f4643 to your computer and use it in GitHub Desktop.
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(value)
subject.send(completion: .finished)
case .failure(let error):
subject.send(completion: .failure(error))
}
}
return subject
}
.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment