Created
November 12, 2020 16:28
-
-
Save vani2/844bd4d5eae7544b0f9432ae992c095f to your computer and use it in GitHub Desktop.
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
final class FetchImageOperation: AsyncOperation { | |
private(set) var result: Result<UIImage, Error>? | |
private lazy var imageProvider = ImageProvider() | |
private let imageID: String | |
init(imageID: String) { | |
self.imageID = imageID | |
super.init() | |
} | |
override func main() { | |
imageProvider.fetchImage(byID: imageID) { [self] url in | |
if let data = try? Data(contentsOf: url), | |
let image = UIImage(data: data) { | |
result = .success(image) | |
} else { | |
result = .failure(NSError(domain: "", code: 0, userInfo: nil)) | |
} | |
state = .finished | |
} | |
} | |
} | |
class Interactor { | |
private(set) var images = [UIImage]() | |
private let imageIDs = [String]() | |
private lazy var operationQueue: OperationQueue = { | |
let opQueue = OperationQueue() | |
opQueue.maxConcurrentOperationCount = 10 | |
return opQueue | |
}() | |
func loadImages(completion: (() -> Void)?) { | |
let operations = imageIDs.map { FetchImageOperation(imageID: $0) } | |
let completedOperation = Operation() | |
completedOperation.completionBlock = { [self] in | |
images = operations.compactMap { try? $0.result?.get() } | |
DispatchQueue.main.async { | |
completion?() | |
} | |
} | |
operations.forEach { completedOperation.addDependency($0) } | |
let allOperations: [Operation] = [completedOperation] + operations | |
operationQueue.addOperations(allOperations, waitUntilFinished: false) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment