This file contains 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
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