Skip to content

Instantly share code, notes, and snippets.

@yoxisem544
Created June 26, 2023 02:45
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 yoxisem544/659068fc35ca28acb27ad9961142042c to your computer and use it in GitHub Desktop.
Save yoxisem544/659068fc35ca28acb27ad9961142042c to your computer and use it in GitHub Desktop.
import Foundation
import Combine
class Driver<Output>: Publisher {
typealias Output = Output
typealias Failure = Never
private let anyPublisher: AnyPublisher<Output, Never>
private var bag = Set<AnyCancellable>()
init(_ anyPublisher: AnyPublisher<Output, Never>) {
self.anyPublisher = anyPublisher
}
func receive<S>(subscriber: S) where S : Subscriber, Never == S.Failure, Output == S.Input {
let subscription = DriverSubscription<S>()
subscription.target = subscriber
subscriber.receive(subscription: subscription)
anyPublisher
.receive(on: DispatchQueue.main)
.sink { [subscription] newValue in
subscription.emit(newValue)
}
.store(in: &bag)
}
}
private extension Driver {
class DriverSubscription<Target: Subscriber>: Subscription {
var target: Target?
func request(_ demand: Subscribers.Demand) {}
func cancel() {
target = nil
}
func emit<Value>(_ value: Value) where Value == Target.Input {
_ = target?.receive(value)
}
}
}
extension Publisher {
func asDriver() -> Driver<Output> where Failure == Never {
Driver(self.eraseToAnyPublisher())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment