Skip to content

Instantly share code, notes, and snippets.

@chris-hatton
Last active March 1, 2017 09:15
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 chris-hatton/ffe600ee5937679935dfa022714e9700 to your computer and use it in GitHub Desktop.
Save chris-hatton/ffe600ee5937679935dfa022714e9700 to your computer and use it in GitHub Desktop.
Simple adaption of Kotlin Coroutines for Android
package somePackage
import android.content.Context
import android.os.Handler
import android.os.Looper
import kotlin.coroutines.experimental.*
var coroutineContext : CoroutineContext? = null
fun initCoroutines( androidContext: Context ) {
coroutineContext = AndroidCoroutineContext( androidContext = androidContext)
}
fun mainCoroutine(body : suspend ()->Unit ) {
coroutineContext?.let {
body.startCoroutine( RootCurrentThreadCoroutine( it ) )
}
}
class AndroidCoroutineContext(val androidContext: Context ) : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> =
AndroidContinuation(continuation, androidContext = androidContext)
}
private class AndroidContinuation<T>(val cont: Continuation<T>, val androidContext: Context) : Continuation<T> by cont {
val handler = Handler( androidContext.mainLooper )
fun isMainLooper() : Boolean {
return Looper.myLooper() == androidContext.mainLooper
}
override fun resume(value: T) {
if ( isMainLooper() ) { cont.resume(value) }
else handler.post { cont.resume(value) }
}
override fun resumeWithException(exception: Throwable) {
if ( isMainLooper() ) { cont.resumeWithException(exception) }
else handler.post { cont.resumeWithException(exception) }
}
}
private class RootCurrentThreadCoroutine(override val context: CoroutineContext): Continuation<Unit> {
override fun resume(value: Unit) {}
override fun resumeWithException(exception: Throwable) {
val currentThread = Thread.currentThread()
currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, exception)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment