【发布时间】:2021-05-21 21:19:43
【问题描述】:
上下文:我发现很少有教程解释如何同时使用 Kotlin 的多个端点,但它们基于 Android,在我的情况下它是一个后端应用程序。我有一些使用 CompleteableFuture 的经验,但我认为我应该使用 Coroutine,因为它是 Kotlin 并且没有 Spring 依赖项。
根据一些建议,我到达了
@Singleton
class PersonEndpoint()
{
@Inject
lateinit var employeClient: EmployeClient
override suspend fun getPersonDetails(request: PersonRequest): PersonResponse {
var combinedResult: String
GlobalScope.launch {
val resultA: String
val resultB: String
val employeesA = async{ employeClient.getEmployeesA()}
val employeesB = async{ employeClient.getEmployeesB()}
try{
combinedResult = employeesA.await() + employeesB.await()
print(combinedResult)
} catch (ex: Exception) {
ex.printStackTrace()
}
// ISSUE 1
if I try add return over here it is not allowed.
I understand it is working how it is designed to work: GlobalScope is running in different thread
}
// ISSUE 2
if I try return combinedResult over here combinedResult isn't initialized.
I understand it is working how it is designed to work: GlobalScope is running in different thread and I can
debug and see that return over here executes earlier than employeesA.await = employeesB.await
}
那么,如何在返回客户端之前执行 combineResult = employeesA.await() + employeesB.await()?
*** 在丹尼斯/回答之后编辑
@Singleton
class CustomerEndpoint(){
fun serve(): Collection<Int> {
return runBlocking {
async {
getItemDouble(1)
}
async {
getItemTriple(1)
}
}.map { it.await() }
}
suspend fun getItemDouble(i: Int): Int {
delay(1000)
return i * 2
}
suspend fun getItemTriple(i: Int): Int {
delay(1000)
return i * 3
}
override suspend fun getPersonDetails(request: PersonRequest): PersonResponse {
val result = serve()
println("Got result $result")
...
}
【问题讨论】:
标签: java kotlin async-await kotlin-coroutines