Search code examples
kotlinspring-webclient

question on kotlin coroutines with webclient


I am new to kotlin. I have written a function that processes two webclient calls in parallel and then aggregates the result. the point is that it is written in a java style (below the code)

@GetMapping("/personv1/{id}")
suspend fun getPerson1(@PathVariable id :Integer): Mono<Person> =
    Mono.zip(
        webClient.get().uri("/person/{id}", id).retrieve().bodyToMono(Person::class.java),
        webClient.get().uri("/person/{id}/domain", id).retrieve().bodyToMono(String::class.java)
    ) { person, domain -> Person(person.id, person.name, domain) }

I wanted to make the same code using coroutines following examples, but I am blocked at the very beginning. My idea was to declare two variables one of type Deferred of a Person and the other one Deferred of a String and then wait for them to merge the data but I am not able to declare any of the variables.

Here is the code I have started

@GetMapping("/personv2/{id}")
suspend fun getPerson2(@PathVariable id :Integer): Person = coroutineScope {
    val person: Deferred<Person> = async {
        webClient
            .get()
            .uri("/person/{id}", id)
            .retrieve()
            .awaitBody<Person>()
    }

}

But my IDE is telling me that my person val should be of type ServerResponse and not a Deferred of Person

Can someone help me on that ? what am I doing wrong?

thanks for your help


Solution

  • Replace async with [email protected].

    There must be some other function in your scope called async that has a higher priority resolution than CoroutineScope.async inside your coroutineScope lambda. The coroutineScope lambda is passed a CoroutineScope as the receiver, so [email protected] will clarify that you specifically mean to call CoroutineScope.async on the receiver of the lambda and not some other async function.

    I'm not familiar with Spring so I don't have any guesses what the other async function is. You might be able to change your imports in this file such that async will resolve to CoroutineScope.async without you having to prefix it with this@coroutineScope. If you want to find out what other function it is resolving to, remove the prefix and Ctrl+Click the function name async and the IDE will take you to the source code for it.