我正在尝试将 REST 服务从 Spring 5 响应式风格转换为异步 Kotlin 协程风格。
我遵循了几个不同的指南/教程,了解这应该如何工作,但我一定做错了什么。
我在尝试将单个对象转换为 Flow 时遇到编译错误,而我遵循的指南似乎根本没有这样做。
任何指示或其他非常感谢!
路由器:
@Bean
fun mainRouter(handler: EobHandler) = coRouter {
GET("/search", handler::search)
GET("/get", handler::get)
}
处理器:
suspend fun search(request: ServerRequest): ServerResponse {
val eobList = service.search()
return ServerResponse.ok().bodyAndAwait(eobList)
}
suspend fun get(request: ServerRequest): ServerResponse
val eob = service.get()
return ServerResponse.ok().bodyAndAwait(eob); // compile error about bodyAndAwait expecting a Flow<T>
}
服务:
override fun search(): Flow<EOB> {
return listOf(EOB()).asFlow()
}
//
override suspend fun get(): EOB? {
return EOB()
}
如果好奇,以下是我基于代码的一些指南:
https://www.baeldung.com/spring-boot-kotlin-coroutines
https://docs.spring.io/spring/docs/5.2.0.M1/spring-framework-reference/languages.html#how-reactive-translates-to-coroutines
https://medium.com/@hantsy/using-kotlin-coroutines-with-spring-d2784a300bda
我能够通过更改来编译它
return ServerResponse.ok().bodyAndAwait(eob);
自
return eob?.let { ServerResponse.ok().bodyValueAndAwait(it) } ?: ServerResponse.notFound().buildAndAwait()
猜猜这与 Kotlin 的类型安全有关 - 我认为我没有返回一个可为空的对象