From 4dcfaf82d88bc51d497cdac70023db8377664442 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20V=C3=A4limaa?= Date: Mon, 14 Oct 2024 16:30:51 +0800 Subject: [PATCH] fix: make ios map view array thread safe --- .../GoogleMapsNavigationViewRegistry.swift | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/ios/Classes/GoogleMapsNavigationViewRegistry.swift b/ios/Classes/GoogleMapsNavigationViewRegistry.swift index 0b2d86d..8b577a5 100644 --- a/ios/Classes/GoogleMapsNavigationViewRegistry.swift +++ b/ios/Classes/GoogleMapsNavigationViewRegistry.swift @@ -14,24 +14,42 @@ class GoogleMapsNavigationViewRegistry { private var views: [Int64: GoogleMapsNavigationView] = [:] + // Using a concurrent queue with a barrier ensures that write operations are serialized, + // meaning each write completes before another write can access the shared resource. + // Multiple read operations can still proceed concurrently as long as no write is in progress. + private let queue = DispatchQueue(label: "thread_safe_queue", attributes: .concurrent) func registerView(viewId: Int64, view: GoogleMapsNavigationView) { - views[viewId] = view + queue.async(flags: .barrier) { [weak self] in + DispatchQueue.main.async { + self?.views[viewId] = view + } + } } func unregisterView(viewId: Int64) { - views.removeValue(forKey: viewId) + queue.async(flags: .barrier) { [weak self] in + DispatchQueue.main.async { + self?.views.removeValue(forKey: viewId) + } + } } func getView(viewId: Int64) -> GoogleMapsNavigationView? { - views[viewId] + queue.sync { + views[viewId] + } } func getAllRegisteredViewIds() -> [Int64] { - Array(views.keys) + queue.sync { + Array(views.keys) + } } func getAllRegisteredViews() -> [GoogleMapsNavigationView] { - Array(views.values) + queue.sync { + Array(views.values) + } } }