Cancel async action with CancelToken in iOS

Sayler8182
Nov 18, 2020
Photo by John Matychuk on Unsplash

Asynchronous work is common in iOS architecture. I’m sure You’ve already used GDC before. Sometimes you want to cancel async operation because you no longer need the result or you just want to stop current work. It can be done by using DispatchWorkItem.

The biggest problem is that You have to use work item inside it’s work method. It’s provide to store object by using optional property that sometime isn’t proper solution.

There is no other build-in method to cancel task from the outside when action is actually running without using DispatchWorkItem. To solve this we have to use workaround and create special ‘token’ that inform us about task status.

All comes down to the proper use of the token. By default action is allowed to run without any restriction but after cancellation task should be stopped. Method can’t be stopped any other way than by checking current status of CancelToken. This solution is great when we run simple async tasks with completion closure, I would rather advise against using it with time-consuming operations because it’s not really stops the actions but checks if action should be dropped.

TL;DR

CancelToken allows you to stop task from the outside.

Fallow for more

In next article I’ll show you more complex example with CancelToken and Version.

Thank you for reading! If you liked this article, please clap so other people can read it too. I will also have more motivation for the next article :) You can also see my other articles, maybe you will find something for you.

If you have any question or suggestion leave a comment.

--

--