Created
July 6, 2020 20:53
-
-
Save vmanot/d549a331f7b9f672ede4ac0e0e89b8a3 to your computer and use it in GitHub Desktop.
AnySubject - Type erasure for Combine's Subject protocol
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 Combine | |
public final class AnySubject<Output, Failure: Error>: Subject { | |
public let base: Any | |
@usableFromInline | |
let _baseAsAnyPublisher: AnyPublisher<Output, Failure> | |
@usableFromInline | |
let _sendImpl: (Output) -> () | |
@usableFromInline | |
let _sendCompletionImpl: (Subscribers.Completion<Failure>) -> () | |
@usableFromInline | |
let _sendSubscriptionImpl: (Subscription) -> () | |
public init<S: Subject>(_ subject: S) where S.Output == Output, S.Failure == Failure { | |
base = subject | |
_baseAsAnyPublisher = subject.eraseToAnyPublisher() | |
_sendImpl = subject.send | |
_sendCompletionImpl = subject.send | |
_sendSubscriptionImpl = subject.send | |
} | |
public func receive<S: Subscriber>(subscriber: S) where Failure == S.Failure, Output == S.Input { | |
_baseAsAnyPublisher.receive(subscriber: subscriber) | |
} | |
public func send(_ value: Output) { | |
_sendImpl(value) | |
} | |
public func send(completion: Subscribers.Completion<Failure>) { | |
_sendCompletionImpl(completion) | |
} | |
public func send(subscription: Subscription) { | |
_sendSubscriptionImpl(subscription) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment