-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathThrottler.swift
46 lines (39 loc) · 1001 Bytes
/
Throttler.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
//
// Throttler.swift
// PovioKit
//
// Created by Domagoj Kulundzic on 1/05/2019.
// Copyright © 2024 Povio Inc. All rights reserved.
//
import Foundation
public class Throttler {
private let queue: DispatchQueue
private var job: DispatchWorkItem?
public var delay: DispatchTimeInterval
public init(queue: DispatchQueue = .main, delay: DispatchTimeInterval) {
self.queue = queue
self.delay = delay
}
}
public extension Throttler {
func execute(work: @escaping () -> Void) {
cancelPendingJob()
let newJob = DispatchWorkItem(block: work)
job = newJob
queue.asyncAfter(deadline: .now() + delay, execute: newJob)
}
func executeWithResult<T>(
work: @escaping () -> T,
completion: @escaping (T) -> Void
) {
cancelPendingJob()
let newJob = DispatchWorkItem {
completion(work())
}
job = newJob
queue.asyncAfter(deadline: .now() + delay, execute: newJob)
}
func cancelPendingJob() {
job?.cancel()
}
}