Skip to content

Instantly share code, notes, and snippets.

@ArnaudPiroelle
Created February 4, 2020 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArnaudPiroelle/e464435d6be3bdeb62e1e56b25ee4fa9 to your computer and use it in GitHub Desktop.
Save ArnaudPiroelle/e464435d6be3bdeb62e1e56b25ee4fa9 to your computer and use it in GitHub Desktop.
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