Created
April 8, 2018 19:15
-
-
Save ashwin-sp/a68265a4705289db26f96f29d5cf53be to your computer and use it in GitHub Desktop.
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
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