How can I wait for Mono to finish so I can utilise generated value

797 Views Asked by At

I want to return the status code from the sendRequest() method instead of just being able to print the value. Could anyone please point out how to modify the code below, to "wait for the Mono to complete"?

I know I can use Thread.sleep(1000); but this really does not seem to be a good approach!

private fun sendRequest(url:String): Disposable {
    val webClient= WebClient.builder().baseUrl(url.trim())
            .defaultHeaders { header: HttpHeaders ->
                header.setBasicAuth("username", "password") }
            .build();

    return webClient.get()
            .uri(url)
            .exchange()
            .map { response: ClientResponse -> response.statusCode() }
            .subscribe { v -> printStatus(v)}
}

fun printStatus(statusMono: HttpStatus) {
    println(statusMono)
}

I know that since I am using WebClient in a Webflux application I must return the Mono or Flux all the way out to the calling client, since it is the calling client that is the subscriber. But I cant find out how.

1

There are 1 best solutions below

0
On BEST ANSWER

@JEY posted the answer above. This worked for me:

webClient.get().uri(url).exchange().map { it.statusCode() }