Created
January 1, 2021 22:01
-
-
Save iosappdeveloper/9d9a7174adfa8c4fa99c5b62dc0ab365 to your computer and use it in GitHub Desktop.
Supports handling of events on a UIControl using Combine framework
This file contains hidden or 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
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