Last active
November 20, 2016 18:08
-
-
Save sys1yagi/91a3aa4067aa969e6a5d2b50f64a43a0 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
package kotlinx.coroutines.android | |
import rx.Observable | |
import rx.android.schedulers.AndroidSchedulers | |
import rx.schedulers.Schedulers | |
fun asyncAndroid( | |
coroutine c: RxController<Unit>.() -> Continuation<Unit> | |
) { | |
val controller = RxController<Unit>() | |
c(controller).resume(Unit) | |
} | |
@AllowSuspendExtensions | |
class RxController<T> internal constructor() { | |
suspend fun <V> Observable<V>.awaitSingle(x: Continuation<V>) { | |
this.single() | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribeWithContinuation(x) | |
} | |
private fun <V> Observable<V>.subscribeWithContinuation(x: Continuation<V>) { | |
subscribe(x::resume, x::resumeWithException) | |
} | |
operator fun handleResult(v: T, x: Continuation<Nothing>) { | |
// no op | |
} | |
operator fun handleException(t: Throwable, x: Continuation<Nothing>) { | |
// no op | |
} | |
} |
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
val userApiClient = UserApiClient() | |
val articleApiClient = ArticleApiClient() | |
val id = 10L | |
asyncAndroid { | |
try { | |
val user = userApiClient.get(id).awaitSingle() // other thread | |
val articles = articleApiClient.getArticles(user).awaitSingle() // other thread | |
binding.result.text = "completed!" // main thread | |
} catch(e: Exception) { | |
binding.result.text = e.message // main thread | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment