diff --git a/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt b/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt index d48b0b020761..d36cb8de9eee 100644 --- a/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt +++ b/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt @@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitSingle import kotlinx.coroutines.reactive.awaitSingle +import kotlinx.coroutines.reactive.awaitSingleOrNull import kotlinx.coroutines.reactor.asFlux import kotlinx.coroutines.reactor.mono import org.reactivestreams.Publisher @@ -143,6 +144,17 @@ suspend inline fun WebClient.ResponseSpec.awaitBody() : T = else -> bodyToMono().awaitSingle() } +/** + * Coroutines variant of [WebClient.ResponseSpec.bodyToMono]. + * + * @author Valentin Shakhov + */ +suspend inline fun WebClient.ResponseSpec.awaitBodyOrNull() : T? = + when (T::class) { + Unit::class -> awaitBodilessEntity().let { Unit as T? } + else -> bodyToMono().awaitSingleOrNull() + } + /** * Coroutines variant of [WebClient.ResponseSpec.toBodilessEntity]. */ diff --git a/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/WebClientExtensionsTests.kt b/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/WebClientExtensionsTests.kt index 6ab3c58ecdbf..ac127c0709e4 100644 --- a/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/WebClientExtensionsTests.kt +++ b/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/WebClientExtensionsTests.kt @@ -136,6 +136,25 @@ class WebClientExtensionsTests { } } + @Test + fun awaitBodyOrNull() { + val spec = mockk() + every { spec.bodyToMono() } returns Mono.just("foo") + runBlocking { + assertThat(spec.awaitBodyOrNull()).isEqualTo("foo") + } + } + + @Test + fun `awaitBodyOrNull of type Unit`() { + val spec = mockk() + val entity = mockk>() + every { spec.toBodilessEntity() } returns Mono.just(entity) + runBlocking { + assertThat(spec.awaitBodyOrNull()).isEqualTo(Unit) + } + } + @Test fun awaitBodilessEntity() { val spec = mockk()