Created
November 21, 2023 10:47
-
-
Save nashysolutions/abd582b82cac86303c26658278509de8 to your computer and use it in GitHub Desktop.
Connectivity monitor using AsyncThrowingStream.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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