https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

voddan

04/23/2018, 2:36 PM
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

Vsevolod Tolstopyatov [JB]

04/23/2018, 3:26 PM
It’s fine. You can optimize it a bit by adding
if (isDone) return get()
before
suspendCancellableCoroutine
v

voddan

04/24/2018, 7:39 AM
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
🙂
8 Views