Future Consume as Suspend

It feels like there should be a way to asynchronously resume after a Worker is done. For example:

val worker = Worker.start()

suspend fun doWork(x: Int): Int {
    return suspendCoroutine { cont ->
        worker.execute(TransferMode.SAFE, { x }) { x ->
            sleep(1u)
            x * 2
        }.consume { res -> cont.resume(res) }
    }
}

This causes other coroutines to freeze while waiting for consume, which is waiting for sleep. It would be much more natural (and efficient) if you could write it like this:

suspend fun <T> Future<T>.await(): T

val worker = Worker.start()

suspend fun doWork(x: Int): Int {
    return worker.execute(TransferMode.SAFE, { x }) { x ->
        sleep(1u)
        x * 2
    }.await()
}

Is there a way to do this with the current API? If not, will it be considered?

Because of the way Native works, since it’s a different thread any object you give it must be frozen first. This means it must be immutable, and so it cannot affect state (so you can’t resume a coroutine). The last lambda passed to execute must also not capture anything, since it is run in a different thread (using const.resume results in a compiler error).

1 Like