Skip to content

Instantly share code, notes, and snippets.

@Thomvis
Last active July 4, 2019 09:01
Show Gist options
  • Save Thomvis/0087f98d61025aaf705fff72e3855ce7 to your computer and use it in GitHub Desktop.
Save Thomvis/0087f98d61025aaf705fff72e3855ce7 to your computer and use it in GitHub Desktop.
UIControlEventPublisher.swift
class ActionTarget {
let handler: () -> Void
init(handler: @escaping () -> Void) {
self.handler = handler
}
@IBAction func handle() {
handler()
}
}
struct AnySubscription: Subscription {
func request(_ demand: Subscribers.Demand) {
_request(demand)
}
func cancel() {
_cancel()
}
var combineIdentifier: CombineIdentifier = CombineIdentifier(NSUUID())
let _request: (Subscribers.Demand) -> Void
let _cancel: () -> Void
}
extension UIControl {
func eventPublisher(for event: UIControl.Event) -> AnyPublisher<UIControl, Never> {
return AnyPublisher { subscriber in
var target: ActionTarget?
subscriber.receive(subscription: AnySubscription(_request: { _ in }, _cancel: {
target = nil
}))
target = ActionTarget {
_ = subscriber.receive(self)
}
self.addTarget(target, action: #selector(ActionTarget.handle), for: event)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment