Member-only story

Operation and Custom Operation

An Operation is a fundamental class used for encapsulating units of work. It's often utilized in scenarios where you need to manage and execute concurrent or asynchronous tasks efficiently.

For example, when you download a game, your phone might first connect to the internet, then start downloading the game files, and finally, install the game. Each of these steps is like a separate operation.

Now, there’s something called an OperationQueue, which is like a to-do list for your phone. It helps your phone manage these tasks by deciding which task should happen first, which can wait, and if they need to happen at the same time.

Let’s create an example that demonstrates downloading multiple images concurrently using Operation and OperationQueue.

First, we’ll create an ImageDownloadOperation class that subclasses Operation to represent the downloading of an image from a URL:

class ImageDownloadOperation: Operation {
let imageUrl: URL
var downloadedImage: UIImage?
init(url: URL) {
self.imageUrl = url
super.init()
}
override func main() {
guard !isCancelled else { return }

do {
let imageData = try Data(contentsOf: imageUrl)
downloadedImage = UIImage(data: imageData)
} catch {
print("Failed to…

--

--

No responses yet