From 228062267a47ca9adf1b1c8cc38da9ba4b1afb66 Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Thu, 8 Dec 2022 18:10:09 +1100 Subject: [PATCH] Avoid duplicated work when first scheduling an update, but then updating now Also might help with duplicated calls to update --- Sources/GeoMonitor/GeoMonitor.swift | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Sources/GeoMonitor/GeoMonitor.swift b/Sources/GeoMonitor/GeoMonitor.swift index b8f42b3..a5f1790 100644 --- a/Sources/GeoMonitor/GeoMonitor.swift +++ b/Sources/GeoMonitor/GeoMonitor.swift @@ -306,12 +306,12 @@ public class GeoMonitor: NSObject, ObservableObject { /// this is called in quick succession. public func scheduleUpdate(regions: [CLCircularRegion]) async { let location = isMonitoring ? (try? await fetchCurrentLocation()) : nil - monitorDebounced(regions, location: location) + monitorDebounced(regions, location: location, delay: 2.5) } public func update(regions: [CLCircularRegion]) async { let location = isMonitoring ? (try? await fetchCurrentLocation()) : nil - monitorNow(regions, location: location) + monitorDebounced(regions, location: location) } /// Trigger a check whether the user is in any of the registered regions and, if so, trigger the primary @@ -390,15 +390,17 @@ extension GeoMonitor { extension GeoMonitor { - func monitorDebounced(_ regions: [CLCircularRegion], location: CLLocation?) { + private func monitorDebounced(_ regions: [CLCircularRegion], location: CLLocation?, delay: TimeInterval? = nil) { monitorTask?.cancel() monitorTask = Task { - try await Task.sleep(nanoseconds: 2_500_000_000) + if let delay { + try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) + } monitorNow(regions, location: location) } } - func monitorNow(_ regions: [CLCircularRegion], location: CLLocation?) { + private func monitorNow(_ regions: [CLCircularRegion], location: CLLocation?) { guard !Task.isCancelled else { return } // Remember all the regions, if it currently too far away