Created
July 27, 2017 14:05
-
-
Save developer--/42562396c78761ee7ca671ecb8f29a10 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 | |
/** | |
* Android Continuation, guarantees that, when resumed, is on the UI Thread | |
* Created by macastiblancot on 2/13/17. | |
*/ | |
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) } | |
} | |
} | |
/** | |
* Android context, provides an AndroidContinuation, executes everything on the UI Thread | |
*/ | |
object Android : 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