简体   繁体   中英

Spring Rest API calling service with Deffered<>

my code functions, but not sure if I am implementing it properly.

I have a service layer that calls Youtrack API using Retrofit, does some post-filtering and returns a list of issues. The code below is simplified version, but should be enough to make a picture.

suspend fun getProjectIssuesFromYt(
    project: String,
    youTrackInstance: YouTrackInstance,
    after: Int,
    max: Int
): List<Issues> = coroutineScope {
    val service = Youtrack.getYoutrack(youTrackInstance).service
    val deferreds: Deferred<List<Issues>> =
        async(Dispatchers.Default) {
            service.getIssuesByProject(
                project = project, max = max,
                after = after
            ).bodyList()
        }
    deferreds.await()
}

How can I call this service from REST api? The only solution that is functioning is to call it with runBlocking , but I don't think this ia a way to go.

@GetMapping("/getProjectIssuesFromYt")
fun getProjectIssuesFromYt(
    project: String,
    youTrackInstance: YouTrackInstance,
    after: Int,
    max: Int
): List<Issues> = runBlocking {
    clientService.getProjectIssuesFromYt(
        project = project,
        youTrackInstance = youTrackInstance,
        after = after,
        max = max
    )
}

I did try making my controller function suspended and running it without runBlocking, but I am getting an error.

"Parameter specified as non-null is null: method kotlinx.coroutines.internal.ScopeCoroutine.<init>, parameter context",

Thank you in advance,

Marko

If you are using Spring MVC: Kotlin Coroutines are only available as an alternative to Java's Project Reactor in Spring Web Flux. Spring MVC Controllers are blocking by design that is why they cannot be implemented as suspending functions. https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM