美文网首页
回调转换为 Kotlin 中的协程

回调转换为 Kotlin 中的协程

作者: 小城哇哇 | 来源:发表于2022-10-24 21:39 被阅读0次

我们将学习如何将任何回调转换为 Kotlin 中的协程。

我们在 Android 项目中使用了许多库,这些库提供了回调方式,而不是协程方式。因此,我们需要学习如何将任何回调转换为 Kotlin 中的协程。

在这里,为了便于理解,我将举一个虚拟库的例子。

假设我们可以按如下方式使用库:

Library.doSomething(object : Listener {

    override fun onSuccess(result: Result) {

    }

    override fun onError(throwable: Throwable) {

    }

})

在这里,库执行一项任务,我们有一个侦听器,通过它我们可以获取和回调。

现在,我们希望以协程方式使用此库。

让我们通过创建如下函数来执行此操作:

suspend fun doSomething(): Result {
    return suspendCoroutine { continuation ->
        Library.doSomething(object : Listener {

            override fun onSuccess(result: Result) {
                continuation.resume(result)
            }

            override fun onError(throwable: Throwable) {
                continuation.resumeWithException(throwable)
            }

        })
    }
}

现在,是时候了解我们做了什么将回调转换为协程了。

我们按照以下步骤将回调转换为 Kotlin 中的协程:

创建一个函数以返回suspendResult
suspendCoroutine用作返回块。
continuation.resume(result)用于成功。
continuation.resumeWithException(throwable)用于错误。
现在,我们可以按如下方式使用上述函数:

launch {
    val result = doSomething()
}

这就是我们如何将任何回调转换为协程并使用它们。

现在,我们将讨论另一件事:它与suspendCancellableCoroutine、suspendCoroutine不同。

假设库也支持取消任务。

val id = Library.doSomething(object : Listener {

    override fun onSuccess(result: Result) {

    }

    override fun onError(throwable: Throwable) {

    }

})

并且,我们可以使用该方法通过Library.cancel(id)
在这种情况下,我们将使用suspendCancellableCoroutine代替suspendCoroutine

现在,再一次,让我们通过创建一个函数来将此回调转换为协程方式,如下所示:

suspend fun doSomething(): Result {
    return suspendCancellableCoroutine { continuation ->
        val id = Library.doSomething(object : Listener {

            override fun onSuccess(result: Result) {
                continuation.resume(result)
            }

            override fun onError(throwable: Throwable) {
                continuation.resumeWithException(throwable)
            }

        })

        continuation.invokeOnCancellation {
            Library.cancel(id)
        }
    }
}

我们遵循的步骤与前面的示例几乎相同,除了以下两件事:

使用suspendCancellableCoroutine代替 suspendCoroutine
continuation.invokeOnCancellation用作我们的库支持取消任务。

continuation.invokeOnCancellation {
    Library.cancel(id)
}

现在,我们可以按如下方式使用上述函数:

launch {
    val result = doSomething()
}

这就是我们如何将任何回调转换为协程并使用它们。

相关文章

网友评论

      本文标题:回调转换为 Kotlin 中的协程

      本文链接:https://www.haomeiwen.com/subject/tpmozrtx.html