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

How to combine existing async requests with RxAndroid or using Kotlin coroutines?

这是我的代码。我有在 SDK 中实现的异步请求。 我正在使用它,我已经实现了调用登录为该异步请求提供回调的简单方法。 我的问题是,是否可以使用 RxAndroid 或 Kotlin Coroutines 组合此异步请求? 因为我将有很多回调链来避免它,所以我正在考虑与 RxJava 或 Kotlin Coroutines 结合使用。 任何参考样本的提示都可以是 goodl

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


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

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

您可以使用 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