You are on page 1of 8

Asynchronous programming with Kotlin

coroutines in Spring

Konrad Kamiński
Allegro.pl
Blocking code
@GetMapping("/users/{userId}/products”)
fun getProducts(@PathVariable userId: String): List<Product> {
if (userValidationService.isValidUser(userId)) {
return productService.getProducts(userId)
} else {
throw UnauthorizedUserException(userId)
}
}

Unless otherwise indicated, these slides are © 2013 -2018 Pivotal Software, Inc. and licensed under a Creative Commons
Attribution-NonCommercial license: http://creativecommons.org/licenses/by -nc/3.0/ 2
Coroutines
suspend fun simpleFun(param: String): Int {
delay(5_000)
return 123
}

fun simpleFun(param: String, callback: Continuation<Int>): Any

interface Continuation<in T> {


val context: CoroutineContext

fun resume(value: T)
fun resumeWithException(exception: Throwable)
}

val COROUTINE_SUSPENDED: Any

Unless otherwise indicated, these slides are © 2013 -2018 Pivotal Software, Inc. and licensed under a Creative Commons
Attribution-NonCommercial license: http://creativecommons.org/licenses/by -nc/3.0/ 3
Coroutines in Spring
@GetMapping("/users/{userId}/products")
suspend fun getProducts(@PathVariable userId: String): List<Product> {
if (userValidationService.isValidUser(userId)) {
return productService.getProducts(userId)
} else {
throw UnauthorizedUserException(userId)
}
}

Unless otherwise indicated, these slides are © 2013 -2018 Pivotal Software, Inc. and licensed under a Creative Commons
Attribution-NonCommercial license: http://creativecommons.org/licenses/by -nc/3.0/ 4
DEMO

https://github.com/konrad-kaminski/spring-kotlin-coroutine

Unless otherwise indicated, these slides are © 2013 -2018 Pivotal Software, Inc. and licensed under a Creative Commons
Attribution-NonCommercial license: http://creativecommons.org/licenses/by -nc/3.0/
Spring 5 + Kotlin coroutines

• Asynchronous application
• Imperative style
• Non-blocking I/O
• Scalability

Unless otherwise indicated, these slides are © 2013 -2018 Pivotal Software, Inc. and licensed under a Creative Commons
Attribution-NonCommercial license: http://creativecommons.org/licenses/by -nc/3.0/ 6
spring-kotlin-coroutine

• @Coroutine and CoroutineContext


• @EventListener & CoroutineEventPublisher
• @Scheduled
• @Cache
• Functional style route definitions

https://github.com/konrad-kaminski/spring-kotlin-coroutine
https://github.com/spring-projects/spring-fu

Unless otherwise indicated, these slides are © 2013 -2018 Pivotal Software, Inc. and licensed under a Creative Commons
Attribution-NonCommercial license: http://creativecommons.org/licenses/by -nc/3.0/ 7
> Stay Connected.

@s1 #springon
p e

You might also like