Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
FutureUtils.kt
package io.robotsdk.model.coroutines.utils
import com.aldebaran.qi.Future
import java.util.concurrent.CancellationException
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
suspend fun <T> Future<T>.await(): T {
if (isDone) return get()
val e = Exception()
e.stackTrace = Thread.currentThread().stackTrace
return suspendCoroutine { continuation: Continuation<T> ->
thenConsume {
when {
it.isSuccess -> continuation.resume(it.value)
it.isCancelled -> {
e.printStackTrace()
continuation.resumeWithException(CancellationException())
}
it.hasError() -> {
e.printStackTrace()
continuation.resumeWithException(it.error)
}
else -> continuation.resumeWithException(RuntimeException("invalid future"))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment