Skip to content

Instantly share code, notes, and snippets.

@developer--
Created July 27, 2017 14:05
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 developer--/42562396c78761ee7ca671ecb8f29a10 to your computer and use it in GitHub Desktop.
Save developer--/42562396c78761ee7ca671ecb8f29a10 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
/**
* 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