【问题标题】:I dont think i am using kotlin JS coroutines correctly我认为我没有正确使用 kotlin JS 协程
【发布时间】:2021-10-02 10:32:39
【问题描述】:

我正在使用 ktor 客户端进行休息呼叫。这是我对服务器的调用

suspend fun fetchCustomerSummary(id: Int)  : Deferred<CustomerPDSummaryDTO> {
    val deffered: Deferred<CustomerPDSummaryDTO> = GlobalScope.async{jsonClient.post<CustomerPDSummaryDTO>("http://localhost:8080/customerSummary"){
        contentType(ContentType.Application.Json)
        body = GenericIntEQ(theInt = id)
    }}
    return deffered
}

这是我如何调用该代码并使用返回的值

GlobalScope.launch {
    setCustomer("")
    val firstRequest = PredictService.fetchCustomerSummary(it.id)
    val result = firstRequest.await()
    props.importReq(result)
}

【问题讨论】:

    标签: kotlin-coroutines ktor


    【解决方案1】:

    我建议创建一个单一作用域并从中调用协程以使structural concurrency 工作。这是一个例子:

    fun main() {
        val scope = MainScope()
        scope.launch {
            val client = HttpClient {
                install(JsonFeature) {
                    serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
                        ignoreUnknownKeys = true
                    })
                }
            }
    
            launch {
                println(client.getOrigin())
            }
    
            val zen = async {
                client.getZen()
            }.await()
    
            println(zen)
        }
    }
    
    suspend fun HttpClient.getOrigin(): String {
        val response = post<BinResponse>("https://httpbin.org/post") {
            body = "123"
        }
        return response.origin
    }
    
    suspend fun HttpClient.getZen(): String {
        return get("https://api.github.com/zen")
    }
    
    @Serializable
    data class BinResponse(val origin: String)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-02
      • 2016-08-08
      • 2017-03-05
      • 1970-01-01
      • 2019-04-06
      • 2021-12-13
      • 2021-08-16
      • 2020-04-29
      相关资源
      最近更新 更多