Network reachability with Combine and Alamofire

NetworkReachabilityHelper
import Alamofire
import Combine
final class NetworkReachabilityHelper {}
private enum Constants {
static let host = "google.com"
}
var reachability = NetworkReachabilityManager(host: Constants.host)
let networkStatus = PassthroughSubject<NetworkReachabilityManager.NetworkReachabilityStatus, Error>()
func startListening() {
reachability?.startListening { [weak self] status in
self
?.networkStatus.send(status)
}
}
func stopListening() {
reachability?.stopListening()
}
var isReachableOnCellular: Bool {
get {
return reachability?.isReachableOnCellular ?? false
}
}
var isReachableOnEthernetOrWiFi: Bool {
get {
return reachability?.isReachableOnEthernetOrWiFi ?? false
}
}
var isReachable: Bool {
get {
return reachability?.isReachable ?? false
}
}
import Alamofire
import Combine
final class NetworkReachabilityHelper {
static let shared = NetworkReachabilityHelper()
private enum Constants {
static let host = "api1.\(Environment.domain)"
}
let networkStatus = PassthroughSubject<NetworkReachabilityManager.NetworkReachabilityStatus, Error>()var reachability = NetworkReachabilityManager(host: Constants.host)var isReachableOnCellular: Bool {
get {
return reachability?.isReachableOnCellular ?? false
}
}
var isReachableOnEthernetOrWiFi: Bool {
get {
return reachability?.isReachableOnEthernetOrWiFi ?? false
}
}
var isReachable: Bool {
get {
return reachability?.isReachable ?? false
}
}
func startListening() {
reachability?.startListening { [weak self] status in
self
?.networkStatus.send(status)
}
}
func stopListening() {
reachability?.stopListening()
}
deinit {
stopListening()
}
}
NetworkReachabilityHelper.shared.networkStatus
.removeDuplicates()
.sink(receiveCompletion: { _ in }, receiveValue: { [weak self] value in
\\\ check status
})
.store(in: &cancelBag)
NetworkReachabilityHelper.shared.isReachable

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store