Real-Serious-Games / C-Sharp-Promise

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

Is there a "mother" class common to every promises? #68

Closed nah0y closed 6 years ago

nah0y commented 6 years ago

Hello again :)

I have these two methods:

    private IEnumerator TimeOutPromiseCoroutine(Promise promise, float timeOut)
    {
        yield return new WaitForSeconds(timeOut);

        if (promise.CurState == PromiseState.Pending)
        {
            promise.Reject(new Exception("Promise has timed out"));
        }
    }

    private IEnumerator TimeOutPromiseCoroutine(Promise<String[]> promise, float timeOut)
    {
        yield return new WaitForSeconds(timeOut);

        if (promise.CurState == PromiseState.Pending)
        {
            promise.Reject(new Exception("Promise has timed out"));
        }
    }

They are identical, except for the first parameter used. Is there a way I can use only one method for both cases?

If this is not clear enough, please tell me, I'll explain it in more details.

sindrijo commented 6 years ago

Currently no. But there should be an easy fix.

Create a new interface (or extend the IRejectable interface, whatever floats your boat):

public interface IStatefulRejectable : IRejectable
{
     PromiseState State { get; }
}

Implement the interface for both PromiseandPromise<T> (I recommend implementing the interface explicitly, if youre not sure what that means just google 'explicit interface implementation c#'.) Then your common method could look something like this:

    private IEnumerator TimeOutPromiseCoroutine(IStatefulRejectable promise, float timeOut)
    {
        yield return new WaitForSeconds(timeOut);

        if (promise.State == PromiseState.Pending)
        {
            promise.Reject(new Exception("Promise has timed out"));
        }
    }

This works because the interfaces expose the information you need, the state of the promise IStatefulRejectable.State and the functionality to reject it. IRejectable.Reject(Exception ex)

NB: I am working on implementing a common base class in my own fork of this project that would enable you to do this, but it is not ready for use yet.

nah0y commented 6 years ago

Thanks a lot for the detailed answer, this looks like a nice solution :)