Last active
June 23, 2020 16:33
-
-
Save bnickel/ef96537c6d59fddd63531641a0959c38 to your computer and use it in GitHub Desktop.
Swift retry operation playground
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 Foundation | |
protocol Completable { | |
func addCompletionOperation(on queue: OperationQueue, complete: @escaping (Self) -> Void) -> Operation | |
} | |
extension Completable where Self: Operation { | |
func addCompletionOperation(on queue: OperationQueue, complete: @escaping (Self) -> Void) -> Operation { | |
let completionOperation = BlockOperation { | |
complete(self) | |
} | |
completionOperation.addDependency(self) | |
queue.addOperation(completionOperation) | |
return completionOperation | |
} | |
} | |
protocol Enqueueable { | |
func enqueue(in queue: OperationQueue) -> Self | |
} | |
extension Enqueueable where Self: Operation { | |
func enqueue(in queue: OperationQueue) -> Self { | |
queue.addOperation(self) | |
return self | |
} | |
} | |
final class NetworkOperation: BlockOperation, Completable, Enqueueable { | |
var result: (URLResponse, Data)? | |
var lastError: Error? | |
init(url: URL, attemptLimit: Int) { | |
super.init() | |
addExecutionBlock { [weak self] in | |
for _ in 1 ... attemptLimit { | |
let request = URLRequest(url: url) | |
do { | |
var response: URLResponse? | |
let data = try NSURLConnection.sendSynchronousRequest(request, returning: &response) | |
self?.result = (response!, data) | |
return | |
} catch { self?.lastError = error } | |
} | |
} | |
} | |
} | |
let networkQueue = OperationQueue() | |
let completionQueue = OperationQueue() | |
NetworkOperation(url: URL(string: "https://google.com")!, attemptLimit: 5) | |
.enqueue(in: networkQueue) | |
.addCompletionOperation(on: completionQueue) { operation in | |
if let (response, data) = operation.result { | |
dump(response) | |
dump(data) | |
} else if let error = operation.lastError { | |
dump(error) | |
} else { | |
dump("¯\\_(ツ)_/¯") | |
} | |
} | |
// Let the playground finish. | |
completionQueue.waitUntilAllOperationsAreFinished() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment