gpt4 book ai didi

kotlin - 使用协程使函数返回回调中获得的值

转载 作者:行者123 更新时间:2023-12-02 13:16:21 25 4
gpt4 key购买 nike

我对异步开发尤其是协程还很陌生。我的意思基本上是,我什至不知道我想要实现的目标是否可能。

我有一个名为 sendAudioMessage 的方法,我想返回一个字符串。这是(混淆的)代码:

override suspend fun sendAudioMessage(): String {
// ... Do some stuff
val listener: WebSocketUtils.Listener = object: WebSocketUtils.Listener {
// ... some (not relevant) functions
override fun onDisconnect(code: Int, reason: String?) {
//Do some stuff
return "myResult -> $code" //This obviously doesn't compile since is trying to make onDisconnect return a string instead of Unit
}
}
}

然后我想这样调用它:

override fun send(request: String) {
CoroutineScope(IO).launch {
val response = d.sendAudioMessage()
analyzeResponse( response, request )
}
}

这可能吗?如果是这样,我该如何实现?

最佳答案

您需要将回调包装在 suspendCancellableCoroutine block 中,以便将阻塞 API 调用转换为暂停函数,这样您就可以从协程中调用它。它是这样工作的:

suspend fun sendAudioMessage(): String = suspendCancellableCoroutine { continuation ->
WebSocketUtils.Listener {
// ... some (not relevant) functions
override fun onDisconnect(code: Int, reason: String?) {
//Do some stuff
when (code) {
OK -> continuation.resume("myResult -> $code")
ERROR -> continuation.resumeWithException(Exception(reason))
}
}
}
}

当您的 API 调用成功返回时,您可以将结果返回给调用 continuation.resume 的协程,并将结果作为参数。

当您的 API 调用返回错误时,您可以抛出异常调用 continuation.resumeWithException

现在您可以在协程中调用 sendAudioMessage 并照常处理其结果:

class MyClass: CoroutineScope by CoroutineScope(Dispatchers.Default) {

...

override fun send(request: String) {
launch(Dispatchers.IO) {
val response = d.sendAudioMessage()
analyzeResponse(response, request)
}
}

...
}

关于kotlin - 使用协程使函数返回回调中获得的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63833665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com