From 0a4f2a11486548acf86e17d93b95c6b9fc7ecc1e Mon Sep 17 00:00:00 2001 From: Alexander Molochko Date: Sun, 15 Sep 2019 17:13:30 +0300 Subject: [PATCH] BAEL-2378 Fix Non-blocking Spring Boot with Kotlin Coroutines --- .../controller/ProductControllerCoroutines.kt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt index d70d352cda..363090abac 100644 --- a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt @@ -5,6 +5,8 @@ import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines import kotlinx.coroutines.Deferred import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.flow.Flow import org.springframework.beans.factory.annotation.Autowired @@ -28,17 +30,17 @@ class ProductControllerCoroutines { } @GetMapping("/{id}/stock") - suspend fun findOneInStock(@PathVariable id: Int): ProductStockView { - val product: Deferred = GlobalScope.async { + suspend fun findOneInStock(@PathVariable id: Int): ProductStockView = coroutineScope { + val product: Deferred = async(start = CoroutineStart.LAZY) { productRepository.getProductById(id) } - val quantity: Deferred = GlobalScope.async { + val quantity: Deferred = async(start = CoroutineStart.LAZY) { webClient.get() .uri("/stock-service/product/$id/quantity") .accept(APPLICATION_JSON) .awaitExchange().awaitBody() } - return ProductStockView(product.await()!!, quantity.await()) + ProductStockView(product.await()!!, quantity.await()) } @FlowPreview