如何将现有的异步请求与RxAndroid结合或使用Kotlin协程?

时间:2019-02-11 15:39:35

标签: android kotlin android-asynctask rx-android kotlin-coroutines

这是我的代码。我有一个在SDK中实现的异步请求。 我正在使用它,我实现了一种简单的方法,即调用login为异步请求提供回调。 我的问题是,是否可以使用RxAndroid或Kotlin Coroutines组合此异步请求? 由于要避免使用许多回调链,因此我想与RxJava或Kotlin Coroutines结合使用。 任何参考样品的提示都可能很好

private fun automaticLogin() {
    UserAction(username, password).login(AutomaticUserLoginRequest(this))
}


class AutomaticUserLoginRequest()
    : UserLoginRequest( object : ILoginResultHandler {
    override fun onSuccess(session: ISession) {
    }

    override fun onError(error: Error) {
    }
  })```

1 个答案:

答案 0 :(得分:1)

您可以使用suspendCoroutine函数来做类似的事情:

suspend fun automaticUserLoginRequest(): ISession {
  return suspendCoroutine<ISession> { cont ->
    callUserLoginRequest(object : ILoginResultHandler {
      override fun onSuccess(session: ISession) {
         cont.resume(session)
      }

      override fun onError(error: Error) {
         cont.resumeWithException(error)
      }
    }
  }
}

您可以从协程执行暂停功能。 kotlinx.coroutines-android为此提供了Dispatchers.UI

fun someFunction() {
   //starts a coroutine, not waiting fro result
   launch(Dispatchers.UI) {

     val session = automaticUserLoginRequest()

     //the execution will resume here once login is done, it can be an exception too
     updateUI(session)
    }
}

https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-android/README.md