We are trying to use Kotlin coroutines for asynchronous processing inside Spring-Boot backend.
The problem is that it doesn't seem to support it well (At least standard Spring MVC).
Basically, if we have a function that does asynchronous logic:
fun fetchUsersAsync(): Deferred<Users> {
return GlobalScope.async {
...
}
}
and this function is used with await
at some point in service, which requires to put suspend
annotation in a calling service function:
@Service
class MyService {
suspend fun processUsers(): Users {
return fetchUsersAsync().await()
}
}
Unfortunately it is not possible, and the only reference for suspend functionality in service was connected with WebFlux.
Has anyone faced the same situation? Thanks.
If you want to call await()
without declaring a suspend
function, wrap it inside a coroutine builder, like this:
@Service
class MyService {
fun processUsers(): Users {
return runBlocking { fetchUsersAsync().await() }
}
}
Sorry for late reply: similar approach worked, thanks!