Skip to content

Instantly share code, notes, and snippets.

@nashysolutions
Created November 21, 2023 10:47
Show Gist options
  • Select an option

  • Save nashysolutions/abd582b82cac86303c26658278509de8 to your computer and use it in GitHub Desktop.

Select an option

Save nashysolutions/abd582b82cac86303c26658278509de8 to your computer and use it in GitHub Desktop.
Connectivity monitor using AsyncThrowingStream.
func monitorChanges() async throws {
let stream = makeStream()
for try await status in stream {
self.status = status
}
}
private func makeStream() -> AsyncThrowingStream<Status, Error> {
AsyncThrowingStream { continuation in
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
continuation.yield(Status(path: path))
}
monitor.start(queue: DispatchQueue.global(qos: .background))
continuation.onTermination = { @Sendable _ in
monitor.cancel()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment