This is a dead-noddy start to a promise-stye API for queuing up Coroutines (and optionally regular functions) to run in series.
Assume you have a Component with functions IEnumerator Foo()
and void Bar()
(that is, a coroutine and a regular function). You can then do this:
var go = new GameObject("CoroutineTests");
var tA = go.AddComponent<PromiseTestComponent>();
var tB = go.AddComponent<PromiseTestComponent>();
tA.Promise(tA.Foo()).Then(tB.Foo()).Then(tA.Bar).Then(tA.Foo()).Then(tB.Bar);```
Note that .Bar
is passed without brackets (i.e. passing the function) but Coroutines are called. This does currently lead to the side effect that the first part of a coroutine (up to the first yield return
) will be called immediately, but I'll work around that in a future version.
If you adopt this pattern across a project then you can expose the returned promise for easy use elsewhere. For example, if you have a component with code like this:
private IEnumerator doThingsSlowly() { .... }
public Promise StartDoingThingsSlowly()
{
return this.Promise(doThingsSlowly());
}
... then you can extend that promise elsewhere, like so:
foo = <get component from somewhere>;
foo.StartDoingThingsSlowly().Then(this.bar); // add an extra job to the chain
Also worth remembering that you can create an inline anonymous function (e.g. to call a function with parameters), so this works for passing arguments to a function:
Promise(foo()).Then(() => Bar(x, y));
The returned Promise
object can be interrupted by calling .Abort()
, and you can check whether it's still running by examining .IsCompleted
and .IsAborted
.