Skip to content

Instantly share code, notes, and snippets.

@iosappdeveloper
Created January 1, 2021 22:01
Show Gist options
  • Save iosappdeveloper/9d9a7174adfa8c4fa99c5b62dc0ab365 to your computer and use it in GitHub Desktop.
Save iosappdeveloper/9d9a7174adfa8c4fa99c5b62dc0ab365 to your computer and use it in GitHub Desktop.
Supports handling of events on a UIControl using Combine framework
extension UIControl {
struct EventPublisher: Publisher {
typealias Output = Void
typealias Failure = Never
fileprivate var control: UIControl
fileprivate var event: Event
func receive<S: Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Failure {
let subscription = EventSubscription<S>()
subscription.target = subscriber
subscriber.receive(subscription: subscription)
control.addTarget(subscription, action: #selector(subscription.trigger), for: event)
}
}
class EventSubscription<S: Subscriber>: Subscription where S.Input == Void {
var target: S?
func request(_ demand: Subscribers.Demand) {}
func cancel() {
target = nil
}
@objc func trigger() {
_ = target?.receive(())
}
}
func publisher(for event: Event) -> EventPublisher {
EventPublisher(control: self, event: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment