Returning Coroutine object to Wait?

uLink has a very fancy Request class that has the following method:

    // Summary:
    //     Use this function to wait for the request to complete, i.e. until Request.isDone
    //     is true, using the Unity coroutine mechanism.  Typically you would call 'yield
    //     return request.WaitUntilDone();' from a coroutine before examining the result
    //     of the request. The coroutine will resume once any given success or error
    //     callback has finished, unless the request was cancelled by the user. Then
    //     the coroutine will resume without any callback being invoked.
    //
    // Returns:
    //     A Coroutine object that can be yielded on from a coroutine.
    public Coroutine WaitUntilDone();

It therefore allows you to do very fancy async database requests using Unity’s coroutines:

IEnumerator Foo()
{
    // doing some db query
    var setRequest = bucket.Set("asdfg", serializedJson);
    yield return setRequest.WaitUntillDone();
    if(setRequest.isSuccessful) Debug.Log("Done & succeeded!");
}

I was wondering how they did it, how exactly do you program such function that returns Coroutine so that it actually does the work in there.

Have a look at my CoroutineHelper. It allows you to “start” coroutines where ever you like. It also has some helper methods to allow all sorts of “default behaviour”. But you can also simply create a coroutine like this:

static IEnumerator _WaitFor(Func<bool> condition)
{
    if (condition == null)
        yield break;
    while (condition())
        yield return null;
}

bool someConditionVariable = false;

public Coroutine WaitFor()
{
    return Run.Coroutine(_WaitFor(()=>someConditionVariable)).WaitFor();
}

This code can be inside any class which doesn’t need to be derived from MonoBehaviour. However you should call WaitFor only from the main thread (so inside another Unity coroutine).