-
Notifications
You must be signed in to change notification settings - Fork 0
/
UIButton+Extension.swift
69 lines (57 loc) · 1.7 KB
/
UIButton+Extension.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
// UIButton+Extension.swift
// CombineCustomPublisherExample
//
// Created by MinKyeongTae on 2022/11/11.
//
import UIKit
import Combine
extension UIControl {
func throttleTapPublisher() -> Publishers.Throttle<UIControl.GesturePublisher<UIControl>, RunLoop> {
return GesturePublisher(control: self, controlEvent: .touchUpInside)
.throttle(
for: .seconds(1),
scheduler: RunLoop.main,
latest: false
)
}
}
extension UIControl {
struct GesturePublisher<Control: UIControl>: Publisher {
typealias Output = Control
typealias Failure = Never
private let control: Control
private let controlEvent: Control.Event
init(control: Control, controlEvent: Control.Event) {
self.control = control
self.controlEvent = controlEvent
}
func receive<S>(subscriber: S) where S : Subscriber, Never == S.Failure, Control == S.Input {
let subscription = GestureSubscription(
subscriber: subscriber,
control: control,
event: controlEvent
)
subscriber.receive(subscription: subscription)
}
}
}
extension UIControl {
final class GestureSubscription<S: Subscriber, Control: UIControl>: Subscription
where S.Input == Control {
private var subscriber: S?
private let control: Control
init(subscriber: S, control: Control, event: UIControl.Event) {
self.subscriber = subscriber
self.control = control
control.addTarget(self, action: #selector(eventHandler), for: event)
}
func request(_ demand: Subscribers.Demand) {}
func cancel() {
subscriber = nil
}
@objc func eventHandler() {
_ = subscriber?.receive(control)
}
}
}