Warm tip: This article is reproduced from stackoverflow.com, please click
kotlin spring-boot kotlin-coroutines

Does Spring-Boot handle Kotlin coroutines apart from WebFlux context?

发布于 2020-03-28 23:17:15

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.

Questioner
Nick Shulhin
Viewed
142
Neo 2020-01-31 17:56

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() }
    }
}