Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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