Skip to content

Instantly share code, notes, and snippets.

@TaLinh
Last active July 6, 2022 13:30
Show Gist options
  • Save TaLinh/ecd433d54e826a1b198ffc3d60dd9eb8 to your computer and use it in GitHub Desktop.
Save TaLinh/ecd433d54e826a1b198ffc3d60dd9eb8 to your computer and use it in GitHub Desktop.
import Network
protocol ConnectionAttribute: Equatable {
init(path: NWPath)
}
class ConnectionObserver<T: ConnectionAttribute> {
var handler: ((T) -> Void)?
private var monitor: NWPathMonitor
private(set) var attribute: T {
didSet {
guard oldValue != attribute else { return }
handler?(attribute)
}
}
deinit {
cancel()
}
init(monitor: NWPathMonitor = NWPathMonitor(),
queue: DispatchQueue = .main,
handler: ((T) -> Void)? = nil) {
self.monitor = monitor
self.attribute = T(path: monitor.currentPath)
self.handler = handler
self.monitor.start(queue: queue)
self.monitor.pathUpdateHandler = { [weak self] path in
self?.attribute = T(path: path)
}
}
func cancel() {
monitor.cancel()
}
}
struct BasicConnectionAttribute: Equatable, ConnectionAttribute {
let isExpensive: Bool
let hasConnection: Bool
init(path: NWPath) {
isExpensive = path.isExpensive
hasConnection = path.status == .satisfied
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment