Real-Serious-Games / C-Sharp-Promise

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

Add support for Progress() handler when promise is Resolved #85

Closed leonidumanskiy closed 5 years ago

leonidumanskiy commented 5 years ago

Currently it is not possible to combine regular promises that report progress with Promise.Resolved().

Consider the following example:

private bool FileIsLoaded(string fileName)
{
    return fileName == "b.txt"; // For demonstration purposes
}

private IPromise LoadFiles()
{
    string fileNames = new string[]{ "a.txt", "b.txt" };
    Promise.All(fileNames.Select(LoadFile))
        .Progress(progress => DisplayProgress(progress));
}

private IPromise<IFileHandler> LoadFile(string fileName)
{
    if(FileIsLoaded(fileName))
    {
        var promise = new Promise<IFileHandler>();
        promise.ReportProgress(1.0f);
        promise.Resolve(_fileCache.GetFile(fileName);
        return promise; // Or even better: return Promise<IFileHandler>.Resolved().ReportProgress(1.0f);
    }
    else
    {
        return LoadFile(fileName);   // Returns IPromise<IFileHandler> with progress changing over time
    }
}

This would fail because All() would try to assign a Progress() handler to the second promise and fail because it's already resolved. So to solve a simple example like that, one would have to make a promise that reports it's progress and resolves itself in the next frame or so.

I can put a MR together, however implementation would require allowing to report a progress on a resolved promise as well, and right now there is a bunch of tests that check that this would not be possible.