Skip to content

Instantly share code, notes, and snippets.

@vmanot
Created July 6, 2020 20:53
Show Gist options
  • Save vmanot/d549a331f7b9f672ede4ac0e0e89b8a3 to your computer and use it in GitHub Desktop.
Save vmanot/d549a331f7b9f672ede4ac0e0e89b8a3 to your computer and use it in GitHub Desktop.
AnySubject - Type erasure for Combine's Subject protocol
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