Home > Software engineering >  Kotlin and Spring - Flow vs Suspend
Kotlin and Spring - Flow vs Suspend

Time:11-01

I am brand new to Kotlin, coming from the Java Spring world. I am looking to replicate Java functionality in Kotlin, that is the normal thread per request model. Looking at the below Kotlin example, I see that one of the methods is flow by default, and for the others they have specified suspend. I have read the docs but am still a bit confused. I have a couple questions to check my understanding:

  • Is there any good reason to force a thread per request model in Kotlin?
  • To force a thread per request model would all functions need to be of type suspend?
  • If I follow the typical spring paradigm* are there any concerns I should have marking all functions with type flow?

*not including state in service classes

@RestController
class UserController(private val userRepository: UserRepository) {

    @GetMapping("/")
    fun findAll(): Flow<User> =
        userRepository.findAll()

    @GetMapping("/{id}")
    **suspend** fun findOne(@PathVariable id: String): User? =
        userRepository.findOne(id) ?:
            throw CustomException("This user does not exist")

    @PostMapping("/")
    **suspend** fun save(user: User) =
        userRepository.save(user)
}

CodePudding user response:

Is there any good reason to force a thread per request model in Kotlin?

There's no good reason not to, and it's usually easier.

To force a thread per request model would all functions need to be of type suspend?

No. You can call normal functions from suspend functions, and likely will. Just don't block.

If I follow the typical spring paradigm* are there any concerns I should have marking all functions with type flow?

Generally you should only mark functions suspend if they actually do something asynchronous, like make an RPC.

  • Related