algoliasearch-client-swift icon indicating copy to clipboard operation
algoliasearch-client-swift copied to clipboard

AsyncOperation cancel() and isCancelled behavior

Open KaiOelfke opened this issue 2 years ago • 0 comments

Summary

The operations returned by the SDK didn't behave as I expected regarding cancellation. I am by no means an expert on the intricacies of (NS)Operation.

AsyncOperation doesn't override isCancelled and doesn't call super.cancel() so isCancelled never becomes true as far as I understand. But there's checks for isCancelled in HTTPRequest and AsyncOperation.start().

I added some unit tests with AsyncOperation and a BlockOperation to see the standard behavior.

To pass the tests I came up with two possible solutions. Either remove the cancel override so that the super implementation of Operation is used or override and manage isCancelled.

Result

With these changes cancellation works as I'd expect. The behavior differs also as the state is not immediately set to finished anymore. Either the operation didn't yet start and will be set to finished once start() is called or the operation is already executing. For the second case it's up to the subclass to optionally handle cancellation and to set the state to finished.

I also added a line in the HTTPRequest isCancelled guard to set the result variable to a cancellation error. So that the completion block gets also called once for an operation that's cancelled early before the URL task is created.

KaiOelfke avatar Oct 04 '22 11:10 KaiOelfke