Skip to content

Instantly share code, notes, and snippets.

@ashwin-sp
Created April 8, 2018 19:15
Show Gist options
  • Save ashwin-sp/a68265a4705289db26f96f29d5cf53be to your computer and use it in GitHub Desktop.
Save ashwin-sp/a68265a4705289db26f96f29d5cf53be to your computer and use it in GitHub Desktop.
import android.os.Handler
import android.os.Looper
import kotlin.coroutines.experimental.AbstractCoroutineContextElement
import kotlin.coroutines.experimental.Continuation
import kotlin.coroutines.experimental.ContinuationInterceptor
private class AndroidContinuation<T>(val cont: Continuation<T>) : Continuation<T> by cont {
override fun resume(value: T) {
if (Looper.myLooper() == Looper.getMainLooper()) cont.resume(value)
else Handler(Looper.getMainLooper()).post { cont.resume(value) }
}
override fun resumeWithException(exception: Throwable) {
if (Looper.myLooper() == Looper.getMainLooper()) cont.resumeWithException(exception)
else Handler(Looper.getMainLooper()).post { cont.resumeWithException(exception) }
}
}
object UI : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> =
AndroidContinuation(continuation)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment