Skip to content

Commit 814aae9

Browse files
authored
Fix crash from continuation being resumed more than once in BackgroundTaskSystemInfo.getNetworkInfo (#16199)
2 parents 29a49f7 + 7fa8a23 commit 814aae9

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

WooCommerce/Classes/Tools/BackgroundTasks/BackgroundTaskRefreshDispatcher.swift

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -173,16 +173,33 @@ private struct BackgroundTaskSystemInfo {
173173
}
174174

175175
private static func getNetworkInfo() async -> NetworkInfo {
176-
return await withCheckedContinuation { continuation in
177-
let monitor = NWPathMonitor()
176+
let monitor = NWPathMonitor()
177+
let queue = DispatchQueue(label: "network.monitor.queue")
178178

179-
monitor.pathUpdateHandler = { path in
180-
monitor.cancel()
181-
continuation.resume(returning: NetworkInfo(path: path))
182-
}
179+
let (stream, continuation) = AsyncStream.makeStream(of: NWPath.self)
180+
181+
monitor.pathUpdateHandler = { path in
182+
continuation.yield(path)
183+
}
183184

184-
let queue = DispatchQueue(label: "network.monitor.queue")
185-
monitor.start(queue: queue)
185+
monitor.start(queue: queue)
186+
187+
defer {
188+
continuation.finish()
189+
monitor.cancel()
190+
}
191+
192+
let timeoutTask = Task {
193+
try await Task.sleep(nanoseconds: 1 * NSEC_PER_SEC)
194+
continuation.finish()
195+
}
196+
197+
if let path = await stream.first(where: { _ in true }) {
198+
timeoutTask.cancel()
199+
return NetworkInfo(path: path)
200+
} else {
201+
// Fallback in case no path is received.
202+
return NetworkInfo(type: "unknown", isExpensive: false, isLowDataMode: false)
186203
}
187204
}
188205
}

0 commit comments

Comments
 (0)