@@ -4,9 +4,9 @@ import com.example.demo.AuthorService
44import com.example.demo.PostService
55import com.example.demo.gql.types.*
66import jakarta.validation.Valid
7+ import kotlinx.coroutines.flow.Flow
8+ import kotlinx.coroutines.flow.flow
79import kotlinx.coroutines.flow.toList
8- import kotlinx.coroutines.reactive.asPublisher
9- import org.reactivestreams.Publisher
1010import org.springframework.graphql.data.method.annotation.*
1111import org.springframework.stereotype.Controller
1212import org.springframework.validation.annotation.Validated
@@ -21,7 +21,7 @@ class PostController(
2121 // Flow is not supported as return type.
2222 // see: https://github.com/spring-projects/spring-graphql/issues/393
2323 @QueryMapping
24- suspend fun allPosts (): List <Post > = postService.allPosts().toList ()
24+ fun allPosts (): Flow <Post > = postService.allPosts()
2525
2626 @QueryMapping
2727 suspend fun postById (@Argument postId : UUID ) = postService.getPostById(postId)
@@ -39,10 +39,13 @@ class PostController(
3939 }
4040
4141 @BatchMapping
42- suspend fun author (posts : List <Post >): List <Author ?> {
43- val keys = posts.map { it.authorId!! }.toList()
44- val authorByIds = authorService.getAuthorByIdIn(keys).toList()
45- return keys.map { k -> authorByIds.firstOrNull { author: Author -> author.id == k } }
42+ suspend fun author (posts : List <Post >): Flow <Author ?> = flow {
43+ posts.forEach { post ->
44+ val author = runCatching {
45+ post.authorId?.let { authorService.getAuthorById(it) }
46+ }.getOrNull()
47+ emit(author)
48+ }
4649 }
4750
4851 @MutationMapping
@@ -57,8 +60,10 @@ class PostController(
5760
5861 // subscription return type does not support Kotlin Flow
5962 // see: https://github.com/spring-projects/spring-graphql/issues/393
63+ // Flow type is supported since Spring for GraphQL 1.3
64+ // and https://github.com/spring-projects/spring-graphql/issues/954
6065 @SubscriptionMapping
61- fun commentAdded (): Publisher <Comment > {
62- return postService.commentAdded().asPublisher()
66+ fun commentAdded (): Flow <Comment > {
67+ return postService.commentAdded()// .asPublisher()
6368 }
6469}
0 commit comments