【问题标题】:Coroutine and Callback handler in kotlinkotlin 中的协程和回调处理程序
【发布时间】:2022-01-18 09:52:11
【问题描述】:

我目前正在使用 AWS 开发工具包构建应用程序。其中一个 API 是登录,除了电子邮件和密码外,还需要一个回调,以便取回请求的状态。问题是我无法发回结果。

这是我的代码:


override suspend fun signIn(email: String, password: String): Result<SignInResult> =
        withContext(ioDispatcher) {
            try {
                api.signIn(email, password, object : Callback<SignInResult> {
                    override fun onResult(result: SignInResult?) {
                        Result.Success(result!!)
                    }

                    override fun onError(e: Exception?) {
                        Result.Error(e!!)
                    }
                })
            } catch (e: Exception) {
                Result.Error(e)
            }
        }


问题是协程登录需要返回Result,但我不知道要返回什么,因为我应该只在onResultonError 和捕获异常时返回。

知道如何让它工作吗?

谢谢

【问题讨论】:

    标签: android kotlin kotlin-coroutines coroutine


    【解决方案1】:

    您可以使用suspendCoroutinesuspendCancellableCoroutine 处理回调:

    override suspend fun signIn(email: String, password: String): Result<SignInResult> = 
        suspendCoroutine { continuation ->
            try {
                api.signIn(email, password, object : Callback<SignInResult> {
                    override fun onResult(result: SignInResult) {
                        // Resume coroutine with a value provided by the callback
                        continuation.resumeWith(Result.Success(result))
                    }
    
                    override fun onError(e: Exception) {
                        continuation.resumeWith(Result.Error(e))
                    }
                })
            } catch (e: Exception) {
                continuation.resumeWith(Result.Error(e))
            }
        }
    

    suspendCoroutine 暂停执行它的协程,直到我们决定通过调用适当的方法 - Continuation.resume... 继续。 suspendCoroutine 主要在我们有一些带有回调的遗留代码时使用。

    还有suspendCancellableCoroutine builder 函数,它的行为类似于suspendCoroutine 的附加功能 - 为块提供CancellableContinuation 的实现。

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2021-03-16
      • 2019-04-13
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多