-
-
Save honghaoz/a38f7679c2242659cc87d788b62f4643 to your computer and use it in GitHub Desktop.
A future publisher backed by a passthrough subject.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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