-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEventForegroundTask.swift
54 lines (48 loc) · 1.46 KB
/
EventForegroundTask.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
import Foundation
final class EventForegroundTask {
private var poller: Poller?
private weak var component: Component?
private let queue: DispatchQueue
init(component: Component?, queue: DispatchQueue) {
self.component = component
self.queue = queue
}
private func reschedule() {
poller?.stop()
guard let component = component else { return }
poller = .init(
intervalMillis: component.config.eventsFlushInterval,
queue: queue,
logger: component.config.logger,
handler: { [weak self] _ in
self?.queue.async {
self?.component?.eventInteractor.sendEvents(force: true, completion: nil)
}
}
)
poller?.start()
}
}
extension EventForegroundTask: ScheduledTask {
func start() {
component?.eventInteractor.set(eventUpdateListener: self)
reschedule()
}
func stop() {
component?.eventInteractor.set(eventUpdateListener: nil)
poller?.stop()
poller = nil
}
}
extension EventForegroundTask: EventUpdateListener {
func onUpdate(events: [Event]) {
queue.async { [weak self] in
self?.component?.eventInteractor.sendEvents(force: false) { result in
guard case .success(let success) = result, success else {
return
}
self?.reschedule()
}
}
}
}