Real-Serious-Games / C-Sharp-Promise

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

To Coroutine #17

Closed mikecann closed 8 years ago

mikecann commented 8 years ago

Hi,

Is there a way to convert a Promise to a Coroutine (to keep consistency with for legacy code)?

Cheers, Mike

ashleydavis commented 8 years ago

Are you using the PromiseTimer?

mikecann commented 8 years ago

Hi Ashley,

No, not yet. I was hoping there was just a simple solution that would apply to any IPromise.

Mike

ashleydavis commented 8 years ago

If you using PromiseTimer then you could call the Update function in the coroutine. That might do what you want.

If you are using a Promise to wrap a true asynchronous operation then it's difficult to use that with a coroutine.

If we exposed an IsResolved property from the Promise class then you could poll that in a coroutine. You are welcome to fork the repo add that and see if it solves your problem. If the code looks good we can bring it back into the main repo.

If your problem was the other way around (how to treat coroutines as promises) then I could give you extensive support. I've just been creating examples of how to do that!

mikecann commented 8 years ago

Hi Ashley,

Okay no worries, I was thinking that perhaps this would do it:

namespace RSG
{
    public static class PromiseExtensions
    {
        public static IEnumerator ToEnumerator(this IPromise promise)
        {
            var done = false;
            promise
                .Done(() => done = true);

            while(!done)
                yield return null;
        }

        public static IEnumerator ToEnumerator<T>(this IPromise<T> promise)
        {
            var done = false;
            promise
                .Done(_ => done = true);

            while (!done)
                yield return null;
        }
    }
}

What do you think?

ashleydavis commented 8 years ago

Awesome. That looks like it should work!

mikecann commented 8 years ago

Ill see if it works in my game then fork and pull request, unless you dont want it in the lib / want to just include it yourself?

LoranceChen commented 8 years ago

@mikecann do you try make a promise under Unity Main thread for some UnityApi action?

mikecann commented 8 years ago

@LoranceChen Im not sure what you mean by that. You could make this run on the main thread if you "Loomed" it