Created
January 17, 2017 15:57
-
-
Save vitorventurin/52125068a0398d04d320c8db991d89e1 to your computer and use it in GitHub Desktop.
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
// | |
// ReachabilityService.swift | |
// RxExample | |
// | |
// Created by Vodovozov Gleb on 10/22/15. | |
// Copyright © 2015 Krunoslav Zaher. All rights reserved. | |
// | |
import RxSwift | |
import Foundation | |
import ReachabilitySwift | |
public enum ReachabilityStatus { | |
case reachable(viaWiFi: Bool) | |
case unreachable | |
} | |
extension ReachabilityStatus { | |
var reachable: Bool { | |
switch self { | |
case .reachable: | |
return true | |
case .unreachable: | |
return false | |
} | |
} | |
} | |
protocol ReachabilityService { | |
var reachability: Observable<ReachabilityStatus> { get } | |
} | |
enum ReachabilityServiceError: Error { | |
case failedToCreate | |
} | |
class DefaultReachabilityService: ReachabilityService { | |
fileprivate let _reachabilitySubject: BehaviorSubject<ReachabilityStatus> | |
var reachability: Observable<ReachabilityStatus> { | |
return _reachabilitySubject.asObservable() | |
} | |
let _reachability: Reachability | |
init() throws { | |
guard let reachabilityRef = Reachability() else { throw ReachabilityServiceError.failedToCreate } | |
let reachabilitySubject = BehaviorSubject<ReachabilityStatus>(value: .unreachable) | |
// so main thread isn't blocked when reachability via WiFi is checked | |
let backgroundQueue = DispatchQueue(label: "reachability.wificheck") | |
reachabilityRef.whenReachable = { reachability in | |
backgroundQueue.async { | |
reachabilitySubject.on(.next(.reachable(viaWiFi: reachabilityRef.isReachableViaWiFi))) | |
} | |
} | |
reachabilityRef.whenUnreachable = { reachability in | |
backgroundQueue.async { | |
reachabilitySubject.on(.next(.unreachable)) | |
} | |
} | |
try reachabilityRef.startNotifier() | |
_reachability = reachabilityRef | |
_reachabilitySubject = reachabilitySubject | |
} | |
deinit { | |
_reachability.stopNotifier() | |
} | |
} | |
extension ObservableConvertibleType { | |
func retryOnBecomesReachable(_ valueOnFailure:E, reachabilityService: ReachabilityService) -> Observable<E> { | |
return self.asObservable() | |
.catchError { (e) -> Observable<E> in | |
reachabilityService.reachability | |
.skip(1) | |
.filter { $0.reachable } | |
.flatMap { _ in | |
Observable.error(e) | |
} | |
.startWith(valueOnFailure) | |
} | |
.retry() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment