Urgent help needed! Is this adaptation of the coro...
# coroutines
v
Urgent help needed! Is this adaptation of the coroutine tutorial correct, or did I miss something?
Copy code
import org.springframework.util.concurrent.ListenableFuture
import org.springframework.util.concurrent.ListenableFutureCallback

public suspend fun <T> ListenableFuture<T>.await(): T = suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
    val callback = ContinuationCallback(cont)
    this.addCallback(callback)
    cont.invokeOnCompletion {
        callback.cont = null // clear the reference to continuation from the future's callback
    }
}

private class ContinuationCallback<T>(@Volatile @JvmField var cont: CancellableContinuation<T>?) : ListenableFutureCallback<T> {
    @Suppress("UNCHECKED_CAST")
    override fun onSuccess(result: T?) { cont?.resume(result as T) }
    override fun onFailure(t: Throwable) { cont?.resumeWithException(t) }
}
v
It’s fine. You can optimize it a bit by adding
if (isDone) return get()
before
suspendCancellableCoroutine
v
Thanks for verifying! I stumbled across a ridiculous bag in my system and the logs suggest that two
suspend
methods executed in the reverse order of how they are written. Glad to know it is not about my
await
🙂