Created
February 4, 2020 10:45
-
-
Save ArnaudPiroelle/e464435d6be3bdeb62e1e56b25ee4fa9 to your computer and use it in GitHub Desktop.
FutureUtils.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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