Nick Shulhin
Nick Shulhin

Reputation: 33

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

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.

Upvotes: 3

Views: 2399

Answers (1)

Neo
Neo

Reputation: 2039

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

Upvotes: 3

Related Questions