Skip to content

Commit e24b2e6

Browse files
Gabrielsdeleuze
authored andcommitted
Add awaitExchangeOrNull extension function to reactive webclient
Closes gh-26778
1 parent aff0d8e commit e24b2e6

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/WebClientExtensions.kt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,15 @@ suspend fun RequestHeadersSpec<out RequestHeadersSpec<*>>.awaitExchange(): Clien
9090
suspend fun <T: Any> RequestHeadersSpec<out RequestHeadersSpec<*>>.awaitExchange(responseHandler: suspend (ClientResponse) -> T): T =
9191
exchangeToMono { mono(Dispatchers.Unconfined) { responseHandler.invoke(it) } }.awaitSingle()
9292

93+
/**
94+
* Variant of [WebClient.RequestHeadersSpec.awaitExchange] that allows a nullable return
95+
*
96+
* @since 5.3.8
97+
*/
98+
@Suppress("DEPRECATION")
99+
suspend fun <T: Any> RequestHeadersSpec<out RequestHeadersSpec<*>>.awaitExchangeOrNull(responseHandler: suspend (ClientResponse) -> T?): T? =
100+
exchangeToMono { mono(Dispatchers.Unconfined) { responseHandler.invoke(it) } }.awaitSingleOrNull()
101+
93102
/**
94103
* Coroutines variant of [WebClient.RequestHeadersSpec.exchangeToFlux].
95104
*

spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/WebClientExtensionsTests.kt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,24 @@ class WebClientExtensionsTests {
103103
}
104104
}
105105

106+
@Test
107+
fun `awaitExchangeOrNull returning null`() {
108+
val foo = mockk<Foo>()
109+
every { requestBodySpec.exchangeToMono(any<Function<ClientResponse, Mono<Foo?>>>()) } returns Mono.empty()
110+
runBlocking {
111+
assertThat(requestBodySpec.awaitExchangeOrNull { foo }).isEqualTo(null)
112+
}
113+
}
114+
115+
@Test
116+
fun `awaitExchangeOrNull returning object`() {
117+
val foo = mockk<Foo>()
118+
every { requestBodySpec.exchangeToMono(any<Function<ClientResponse, Mono<Foo>>>()) } returns Mono.just(foo)
119+
runBlocking {
120+
assertThat(requestBodySpec.awaitExchangeOrNull { foo }).isEqualTo(foo)
121+
}
122+
}
123+
106124
@Test
107125
fun exchangeToFlow() {
108126
val foo = mockk<Foo>()

0 commit comments

Comments
 (0)