Last active
March 1, 2017 09:15
-
-
Save chris-hatton/ffe600ee5937679935dfa022714e9700 to your computer and use it in GitHub Desktop.
Simple adaption of Kotlin Coroutines for Android
This file contains hidden or 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 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