Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Last active November 20, 2016 18:08
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 sys1yagi/91a3aa4067aa969e6a5d2b50f64a43a0 to your computer and use it in GitHub Desktop.
Save sys1yagi/91a3aa4067aa969e6a5d2b50f64a43a0 to your computer and use it in GitHub Desktop.
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
}
}
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