asynchronous - 在 Kotlin 中等待多个回调/lambdas 的结果

标签 asynchronous kotlin okhttp

我正在用 Kotlin 制作一个应用程序。到目前为止,我的网络调用不必一起使用。我现在需要进行两个并发网络调用,暂停直到我收到他们的两个响应,然后继续执行。我正在尝试完成这样的事情:

    //first networking call, get resourceOne
    var resourceOne : String?
    Server.asyncRequest(RequestBuilder(endpoints.second, ids, params)) { resource: String?, error: ServiceError? ->
        resourceOne = resource
    }

    //second networking call, get resourceTwo
    var resourceTwo : String?
    Server.asyncRequest(RequestBuilder(endpoints.third, ids, params)) { resource: String?, error: ServiceError? ->
        resourceTwo = resource
    }

    //do something here wiith resourceOne and resourceTwo

我的 asyncRequest 函数的函数头是:
fun asyncRequest(requestBuilder: RequestBuilder, completion: (resource: String?, error: ServiceError?) -> Unit) {

它只是围绕一个 okhttp 请求并进行一些额外的处理/解析。通常我只会获取结果(资源)并在完成 lambda 内部处理它,但由于我需要这两个值,我不能在这里这样做。我试过做类似 this 的事情但是我的 asyncRequest 函数没有返回类型,所以我无法像链接那样执行异步/等待。

最佳答案

你可以用 来做协程 连同 流量像这样:

回调进入 可悬挂功能 suspendCancellableCoroutine {...}堵塞:

suspend fun <T> request(requestBuilder: RequestBuilder): T = suspendCancellableCoroutine { cont ->
    Server.asyncRequest(requestBuilder) { resource: T, error: ServiceError? ->
        if(error != null)
            cont.resumeWithException(error) // Makes the Flow throw an exception
        else
            cont.resume(resource) // Makes the Flow emit a correct result
    }
}

创建一个 流量制作 第一个请求 :
val resourceOneFlow = flow {
    emit(request<String>(RequestBuilder(endpoints.second, ids, params)))
}

创建一个 流量制作 第二个请求 :
val resourceTwoFlow = flow {
    emit(request<String>(RequestBuilder(endpoints.third, ids, params)))
}

联合 两者 流量 zip运算符(operator):
val requestsResultFlow = resourceOneFlow.zip(resourceTwoFlow) { resourceOne, resourceTwo ->
    // Build whatever you need with resourceOne and resourceTwo here and let it flow
    "$resourceOne $resourceTwo".length // Here I concatenate both strings and return its length
}

激活/启动 流量collect运算符并使用其 结果 :
requestsResultFlow.collect { length ->
    // Consume the result here
    println("$length") // Here I print the number received
}

您有 流量文档 here .

关于asynchronous - 在 Kotlin 中等待多个回调/lambdas 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60551996/

相关文章:

kotlin - 如何生成一个类,该类扩展了一个使用 kotlinpoet 实现通用接口(interface)的类

kotlin - 如何在 Jetpack Compose 中很好地从数据库初始化状态?

android - okhttp中无法解析MultipartBuilder :3. 0.0-RC1

linux - 正确处理 libaio 回调中的上下文数据?

javascript - Node js async.series 不适用于 Express 应用程序 --- 响应发生得太快

java - 为什么 Kotlin 字节码会引用 java.util.function.BiConsumer?

Android 使用 OkHttp 和协程下载多个文件

java.io.IOException : unexpected end of stream on Connection? 异常

node.js - 意外行为 - IIFE 需要时异步等待?

javascript - jQuery 文档就绪 - 函数调用 : sequential or asynch?