Real-Serious-Games / C-Sharp-Promise

Promises library for C# for management of asynchronous operations.
MIT License
1.19k stars 149 forks source link

Cancelling a promise. #105

Closed ostryhub closed 4 years ago

ostryhub commented 4 years ago

Hi I have a simple questions - can you cancel a promise ?

Why I am asking: Say I have a view that when showed asks some resource manager for the list of image promises (through the presenter of some sort...).

I am only interested in promises resolving when the view is active and presented. Now lets say the view gets hidden before some promises make it back with the images.

Am I able to unregister from those promises "resolvation" or maybe keep the promise reference and cancel it when no longer needed (when the prsenter of the view is notified that its getting hidden).

Is there any way to cancel a scheduled promise ?

Thanks !

RoryDungan commented 4 years ago

The library currently has no way to cancel promises. We've based our implementation on JavaScript promises, which have no built in function for cancellation. That said, some 3rd party JS promise libraries have added this feature and we aren't opposed to adding our own features on top of the promise spec to this library too as long as it remains compatible with standard promises.

The good thing is that implementing cancellation for a promise yourself isn't too hard. Basically all you'll need to do is store a token somewhere and check it in your promise callback, throwing an exception if it is true.

bool cancellationToken = false;
var promise = SomeOperationThatTakesTime()
    .Then(url => 
    {
        if (cancellationToken)
        {
            throw new CancelledException();
        }
        return DownloadImage(url);
    })
    .Catch(ex => 
    {
        if (ex is CancelledException)
        {
            Debug.Log("Promise cancelled");
            return;
        }
        throw ex;
    })
    .Done();
cancellationToken = true;

Alternatively, if you want a solution that's similar to promises but has cancellation built-in, I'd recommend checking out Rx Observables. If you're using Unity you can use UniRx.