Make CoalescingQueue nonisolated and Sendable.

This commit is contained in:
Brent Simmons committed 2025-11-12 10:18:24 -08:00
1 parent 67a9058eef
commit 78ebf4e698
1 file changed
+70 -34
@@ -7,39 +7,51 @@
//
import Foundation
import Synchronization
// Use when you want to coalesce calls for something like updating visible table cells.
// Calls are uniqued. If you add a call with the same target and selector as a previous call, you’ll just get one call.
// Targets are weakly-held. If a target goes to nil, the call is not performed.
// The perform date is pushed off every time a call is added.
// Calls are FIFO.
// Thread-safe: can be called from any thread, but performs calls on main thread.
struct QueueCall: Equatable {
weak var target: AnyObject?
let selector: Selector
func perform() {
@MainActor func perform() {
let _ = target?.perform(selector)
}
static func ==(lhs: QueueCall, rhs: QueueCall) -> Bool {
return lhs.target === rhs.target && lhs.selector == rhs.selector
}
}
@objc public final class CoalescingQueue: NSObject {
nonisolated public final class CoalescingQueue: Sendable {
public static let standard = CoalescingQueue(name: "Standard", interval: 0.05, maxInterval: 0.1)
public let name: String
public var isPaused = false
private let interval: TimeInterval
private let maxInterval: TimeInterval
private var lastCallTime = Date.distantFuture
private var timer: Timer? = nil
private var calls = [QueueCall]()
private struct State {
var isPaused = false
var lastCallTime = Date.distantFuture
var timer: Timer? = nil
var calls = [QueueCall]()
}
private let state = Mutex(State())
public var isPaused: Bool {
get {
state.withLock { $0.isPaused }
}
set {
state.withLock { $0.isPaused = newValue }
}
}
public init(name: String, interval: TimeInterval = 0.05, maxInterval: TimeInterval = 2.0) {
self.name = name
@@ -49,49 +61,73 @@ struct QueueCall: Equatable {
public func add(_ target: AnyObject, _ selector: Selector) {
let queueCall = QueueCall(target: target, selector: selector)
add(queueCall)
if Date().timeIntervalSince1970 - lastCallTime.timeIntervalSince1970 > maxInterval {
timerDidFire(nil)
let shouldFireImmediately = state.withLock { state -> Bool in
_add(queueCall, state: &state)
return Date().timeIntervalSince1970 - state.lastCallTime.timeIntervalSince1970 > maxInterval
}
if shouldFireImmediately {
timerDidFire()
}
}
public func performCallsImmediately() {
guard !isPaused else { return }
let callsToMake = calls // Make a copy in case calls are added to the queue while performing calls.
resetCalls()
callsToMake.forEach { $0.perform() }
let callsToMake = state.withLock { state -> [QueueCall]? in
guard !state.isPaused else { return nil }
let calls = state.calls
state.calls = []
return calls
}
guard let callsToMake else { return }
// Always perform calls on main thread
if Thread.isMainThread {
MainActor.assumeIsolated {
callsToMake.forEach { $0.perform() }
}
} else {
DispatchQueue.main.async {
callsToMake.forEach { $0.perform() }
}
}
}
@objc func timerDidFire(_ sender: Any?) {
lastCallTime = Date()
func timerDidFire() {
state.withLock { $0.lastCallTime = Date() }
performCallsImmediately()
}
}
private extension CoalescingQueue {
func add(_ call: QueueCall) {
restartTimer()
private func _add(_ call: QueueCall, state: inout State) {
_restartTimer(state: &state)
if !calls.contains(call) {
calls.append(call)
if !state.calls.contains(call) {
state.calls.append(call)
}
}
func resetCalls() {
calls = [QueueCall]()
private func _restartTimer(state: inout State) {
_invalidateTimer(state: &state)
// Schedule timer on main thread
DispatchQueue.main.async { [weak self] in
guard let self else { return }
self.state.withLock { state in
state.timer = Timer.scheduledTimer(withTimeInterval: self.interval, repeats: false) { [weak self] _ in
self?.timerDidFire()
}
}
}
}
func restartTimer() {
invalidateTimer()
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(timerDidFire(_:)), userInfo: nil, repeats: false)
}
func invalidateTimer() {
if let timer = timer, timer.isValid {
private func _invalidateTimer(state: inout State) {
if let timer = state.timer, timer.isValid {
timer.invalidate()
}
timer = nil
state.timer = nil
}
}