Created
December 19, 2017 07:37
-
-
Save revdfdev/30b607a69cda6ffa918824c16f629a35 to your computer and use it in GitHub Desktop.
Coroutines basic
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 com.webcubictechnologies.bellmaison.coroutines | |
| import android.os.Handler | |
| import android.os.Looper | |
| import kotlinx.coroutines.experimental.CommonPool | |
| import kotlinx.coroutines.experimental.Deferred | |
| import kotlinx.coroutines.experimental.async | |
| import kotlinx.coroutines.experimental.delay | |
| import kotlin.coroutines.experimental.AbstractCoroutineContextElement | |
| import kotlin.coroutines.experimental.Continuation | |
| import kotlin.coroutines.experimental.ContinuationInterceptor | |
| /** | |
| * Created by webcubictech2 on 18/12/17. | |
| */ | |
| class AndroidContinuation<in T>(private val continuation: Continuation<T>): Continuation<T> by continuation { | |
| override fun resume(value: T) { | |
| if (Looper.myLooper() == Looper.getMainLooper()) continuation.resume(value) | |
| else Handler(Looper.getMainLooper()).post { continuation.resume(value) } | |
| } | |
| override fun resumeWithException(exception: Throwable) { | |
| if (Looper.myLooper() == Looper.getMainLooper()) continuation.resumeWithException(exception) | |
| else Handler(Looper.getMainLooper()).post { continuation.resumeWithException(exception) } | |
| } | |
| } | |
| object UI: AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor { | |
| override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = AndroidContinuation(continuation) | |
| } | |
| inline fun<T> bg(crossinline f: () -> T): Deferred<T> { | |
| return async(CommonPool) { | |
| delay(500) | |
| f() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment