Created
June 26, 2023 02:45
-
-
Save yoxisem544/659068fc35ca28acb27ad9961142042c to your computer and use it in GitHub Desktop.
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 | |
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