Skip to content

Repository files navigation

TaskStore

A Store where you can temporarily hold the tasks that describes in Swift concurrency. It is useful when you want to cancel specific tasks at the appropriate points.

For example, it can be used to fetch the image for UITableViewCell using Task.
In this case, we require to cancel the Task, however, it's not that simple without other implementation changes.
The following shows example code how to resolve this problem by storing the tasks. Plus, it is a way that reaches out the goal with only additional code, no removed code.

Before

overridefunc tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath)->UITableViewCell{letcell= tableView.dequeueReusableCell(CustomCell.self, for: indexPath)Task{guardlet response =await network.request(url: url)else{return}guardlet imageURL =URL(string: response.imageURL)else{return}letimage=await imageLoader.load(from: imageURL)
cell.update(image: image)}return cell
}

After

overridefunc tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath)->UITableViewCell{letcell= tableView.dequeueReusableCell(CustomCell.self, for: indexPath)
// ✨ For identifing tasks
letcellID=ObjectIdentifier(cell)
// ✨ Cancel tasks that no longer needs
taskStore.tasks(where:{ $0.cellID == cellID }).forEach{ $0.cancel()}
// ✨ Assign to variable
letimageUpdateTask=Task{guardlet response =await network.request(url: url)else{return}tryTask.checkCancellation() // ✨ Check cancellation at the appropriate time.
guardlet imageURL =URL(string: response.imageURL)else{return}letimage=await imageLoader.load(from: imageURL)tryTask.checkCancellation() // ✨ Check cancellation at the appropriate time.
cell.update(image: image)}
// ✨ Store a task taskStore.setTask(imageUpdateTask, forKey:CellImageUpdateKey(cellID: cellID, indexPath: indexPath))return cell
}

You can use it anywhere you want to store a Task, not just in the example above!

Features

  • The stored tasks are automatically removed from the store when it completed.("Removed" means to removed from memory and can't access anymore)

How it works?

When you store the task, it creates a parent task that will deallocate the stored one. This parent task is waiting for the associated task(the stored task) completed or cancelled, and it has lowest priority so that executes in the background.

image

Contribution

Welcome any contributions via issue or pull request, such as any features you'd like to see added, bug reports, etc. 🙌

Installation

dependencies:[.package(url:"https://github.com/woin2ee/TaskStore.git",.upToNextMajor(from:"0.1.0"))]

About

A Store where you can temporarily hold the tasks that describes in Swift concurrency. It is useful when you want to cancel specific tasks at the appropriate points.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages