BFTask
has been good to me but I have one complaint: I've yet to see a working example of how you ought to cancel
a task. The entirety of the documentation on the subject is found on their GitHub page with a single lowly section that includes everything but the part I care about: how to cancel the task.
// Somewhere else.
MYCancellationToken *cancellationToken = [[MYCancellationToken alloc] init];
[obj doSomethingComplicatedAsync:cancellationToken];
// When you get bored...
[cancellationToken cancel];
Their code snippet is followed by:
Note: The cancellation token implementation should be thread-safe.
I am wondering the following:
- Is there a good reason that they may not have provided the
cancel
method on theBFTask
interface itself? They have a property representing whether the task was canceled but no means to cancel it. - Is there a good reason that they would not include a
cancellationToken(s)
property on theBFTask
itself? - Is the implementation of
cancel
strongly coupled to the task itself? Or is a general implementation possible as in the case ofcancelAllOperations
of anNSOperationQueue
?
BFTask
is an implementation of the Future and Promises construct:"a future is a read-only placeholder view of a variable, while a promise is a writable, single assignment container which sets the value of the future".
Basically, a
BFTask
is aFuture
: it is a read-only placeholder view of a variable.A
BFTaskCompletionSource
is a promise: it is a writable, single assignment container which sets the value of the future. (or an error - or cancels the task)The
BFTask
public interface remains read-only , hence it does not allow you to cancel it directly.BFCancellationToken
token just stores a state, which theBFTask
can check. Your async task code can basically regularly checkcancellationRequested
is set to true, which allows you to manually cancel your task.Note: The Bolts Framework iOS docs say: "A task is kind of like a JavaScript Promise" which can be confusing, because it really is a Future. I think it was just named wrong in its Javascript origins.