Last active
July 7, 2019 12:57
-
-
Save myobie/417316a56274ba06d63107c9e8a15f37 to your computer and use it in GitHub Desktop.
Subscribers.Sink sucks, so this will receive forever until completion
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
import Foundation | |
import Combine | |
extension Subscribers { | |
final public class Forever<Upstream: Publisher>: Subscriber, Cancellable, CustomStringConvertible { | |
public typealias Input = Upstream.Output | |
public typealias Failure = Upstream.Failure | |
private var subscription: Subscription? = nil | |
private let receiveCompletion: (Subscribers.Completion<Failure>) -> Void | |
private let receiveValue: (Input) -> Void | |
public var hasSubscription: Bool { subscription != nil } | |
public var description: String { | |
"Subscribers.Forever(\(combineIdentifier), \(hasSubscription ? "has subscription" : "not yet subscribed"))" | |
} | |
public init(receiveCompletion: @escaping (Subscribers.Completion<Failure>) -> Void, | |
receiveValue: @escaping (Input) -> Void) { | |
self.receiveCompletion = receiveCompletion | |
self.receiveValue = receiveValue | |
} | |
public func receive(_ input: Input) -> Subscribers.Demand { | |
receiveValue(input) | |
return .unlimited | |
} | |
public func receive(completion: Subscribers.Completion<Upstream.Failure>) { | |
receiveCompletion(completion) | |
} | |
public func receive(subscription: Subscription) { | |
guard self.subscription == nil else { return subscription.cancel() } | |
self.subscription = subscription | |
subscription.request(.unlimited) | |
} | |
public func cancel() { | |
subscription?.cancel() | |
self.subscription = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment