Last active
July 4, 2019 09:01
-
-
Save Thomvis/0087f98d61025aaf705fff72e3855ce7 to your computer and use it in GitHub Desktop.
UIControlEventPublisher.swift
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
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