Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Network constraint #332

Merged
merged 1 commit into from
May 30, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 14 additions & 16 deletions Sources/SwiftQueue/Constraint+Network.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public enum NetworkType: Int, Codable {
}

#if os(iOS) || os(macOS) || os(tvOS)
internal final class NetworkConstraint: JobConstraint {
internal final class NetworkConstraint: SimpleConstraint {

/// Require a certain connectivity type
internal let networkType: NetworkType
Expand All @@ -48,36 +48,34 @@ internal final class NetworkConstraint: JobConstraint {
self.networkType = networkType
}

func willSchedule(queue: SqOperationQueue, operation: SqOperation) throws {
override func willSchedule(queue: SqOperationQueue, operation: SqOperation) throws {
assert(operation.dispatchQueue != .main)
self.reachability = try Reachability(targetQueue: operation.dispatchQueue, notificationQueue: operation.dispatchQueue)
}

func willRun(operation: SqOperation) throws {
guard let reachability = reachability else { return }
guard hasCorrectNetwork(reachability: reachability) else {
try reachability.startNotifier()
return
}
}
override func run(operation: SqOperation) -> Bool {
guard let reachability = reachability else { return true }

func run(operation: SqOperation) -> Bool {
guard let reachability = reachability else {
if (hasCorrectNetwork(reachability: reachability)) {
return true
}

if hasCorrectNetwork(reachability: reachability) {
return true
}
operation.logger.log(.verbose, jobId: operation.name, message: "Unsatisfied network requirement")

reachability.whenReachable = { reachability in
reachability.stopNotifier()
reachability.whenReachable = nil
operation.run()
}

operation.logger.log(.verbose, jobId: operation.name, message: "Unsatisfied network requirement")
return false
do {
try reachability.startNotifier()
return false
} catch {
operation.logger.log(.verbose, jobId: operation.name, message: "Unable to start network listener. Job will run.")
operation.logger.log(.error, jobId: operation.name, message: error.localizedDescription)
return true
}
}

private func hasCorrectNetwork(reachability: Reachability) -> Bool {
Expand Down