SlideShare a Scribd company logo
Tackling Asynchrony
with Kotlin Coroutines
Presented By: PRAVEER GUPTA
fun getUserAddress(userId: Long): Address { … }
fun getRestaurants(address: Address): List<Restaurant> { … }
Sync or Async?
Reactive approach to Async
fun getUserAddress(userId: Long): Single<Address> { … }
fun getRestaurants(address: Address): Single<List<Restaurant>> { … }
Wrapped return types
Kotlin Coroutine’s approach to Async
suspend fun getUserAddress(userId: Long): Address { … }
suspend fun getRestaurants(address: Address): List<Restaurant> { … }
Suspend modifier
Sync API Usage
fun showUserRestaurants(userId: Long) {
val address = getUserAddress(userId)
val restaurants = getRestaurants(address)
processRestaurants(restaurants)
}
fun getUserAddress(userId: Long): Address { … }
fun getRestaurants(address: Address): List<Restaurant> { … }
Sequential & blocking
fun showUserRestaurants(userId: Long) {
getUserAddress(userId)
.flatMap { address -> getRestaurants(address) }
.subscribe { restaurants -> processRestaurants(restaurants) }
}
Reactive API Usage
fun getUserAddress(userId: Long): Single<Address> { … }
fun getRestaurants(address: Address): Single<List<Restaurant>> { … }
Chained operators
& actions
Kotlin Coroutine API Usage
suspend fun showUserRestaurants(userId: Long) {
val address = getUserAddress(userId)
val restaurants = getRestaurants(address)
processRestaurants(restaurants)
}
suspend fun getUserAddress(userId: Long): Address { … }
suspend fun getRestaurants(address: Address): List<Restaurant> { … }
Suspend modifier
Comparison
suspend fun showUserRestaurants(userId: Long) {
val address = getUserAddress(userId)
val restaurants = getRestaurants(address)
processRestaurants(restaurants)
}
suspend fun getUserAddress(userId: Long): Address { … }
suspend fun getRestaurants(address: Address): List<Restaurant> { … }
fun showUserRestaurants(userId: Long) {
val address = getUserAddress(userId)
val restaurants = getRestaurants(address)
processRestaurants(restaurants)
}
fun getUserAddress(userId: Long): Address { … }
fun getRestaurants(address: Address): List<Restaurant> { … }
Synchronous
Asynchronous
using
Kotlin
Coroutines
Structure of
imperative synchronous code
is the same as
asynchronous code
(taken from KotlinConf 2018 - Exploring Coroutines in Kotlin by Venkat Subramaniam available on
YouTube)
Kotlin Coroutines
Kotlin Coroutines
No restructuring of code to a different paradigm
Reuse existing language control flows
Sequential vs Concurrent execution with coroutines
Complexities of async programming that coroutines handles
Kotlin Coroutines 101
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}
Output:
Hello
World!
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}
Coroutine Builders
Coroutine - an instance
of a suspendable
computation
Kotlin Coroutines 101
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}
Suspending
function suspends
the execution of
the coroutine
Kotlin Coroutines 101
Suspended coroutine
resumes with a
continuation block
public interface Continuation<in T> {
public val context: CoroutineContext
public fun resumeWith(result: Result<T>)
}
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}
Kotlin Coroutines 101
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
doWorld()
}
println("Hello")
}
private suspend fun doWorld() {
delay(1000L)
println("World!")
}
Suspending function is
marked with a
suspend modifier
Kotlin Coroutines 101
org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2
org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.2
org.jetbrains.kotlinx:kotlinx-coroutines-reactive:1.3.2
Core Library
Integrations
Kotlin Coroutines 101
suspend fun showUserRestaurants(userId: Long) {
val address = getUserAddress(userId)
val restaurants = getRestaurants(address)
processRestaurants(restaurants)
}
Reuse existing Control flows
How can you make the below
method resilient to failures?
suspend fun showUserRestaurants(userId: Long) {
try {
val address = withTimeout(200L) { getUserAddress(userId) }
val restaurants = withTimeout(300L) { getRestaurants(address) }
processRestaurants(restaurants)
} catch (e: TimeoutCancellationException) {
// handle exception here
}
}
Exception handling using
standard try-catch block
Reuse existing Control flows
Sequential vs Concurrent
suspend fun showUserDetails(userId: Long) {
val userInfo = getUserInfo(userId)
val orders = getUserOrders(userId)
combineAndBuild(userInfo, orders)
}
Two independent
calls to
external system
suspend fun getUserInfo(userId: Long): UserInfo { … }
suspend fun getUserOrders(userId: Long): List<Order> { … }
suspend fun showUserDetails(userId: Long) {
val userInfo = getUserInfo(userId)
val orders = getUserOrders(userId)
combineAndBuild(userInfo, orders)
}
Sequential vs Concurrent
suspend fun getUserInfo(userId: Long): UserInfo { … }
suspend fun getUserOrders(userId: Long): List<Order> { … }
first suspension
Sequential vs Concurrent
suspend fun getUserInfo(userId: Long): UserInfo { … }
suspend fun getUserOrders(userId: Long): List<Order> { … }
suspend fun showUserDetails(userId: Long) {
val userInfo = getUserInfo(userId)
val orders = getUserOrders(userId)
combineAndBuild(userInfo, orders)
}
second suspension
Sequential vs Concurrent
suspend fun getUserInfo(userId: Long): UserInfo { … }
suspend fun getUserOrders(userId: Long): List<Order> { … }
suspend fun showUserDetails(userId: Long) {
val userInfo = getUserInfo(userId)
val orders = getUserOrders(userId)
combineAndBuild(userInfo, orders)
}
final call
Sequential vs Concurrent
suspend fun showUserDetails(userId: Long) {
val userInfo = getUserInfo(userId)
val orders = getUserOrders(userId)
combineAndBuild(userInfo, orders)
}
suspend fun getUserInfo(userId: Long): UserInfo { … }
suspend fun getUserOrders(userId: Long): List<Order> { … }
sequential
execution
by default
Sequential vs Concurrent
suspend fun showUserDetails(userId: Long) {
coroutineScope {
val userInfo = async { getUserInfo(userId) }
val orders = async { getUserOrders(userId) }
combineAndBuild(userInfo.await(), orders.await())
}
}
suspend fun getUserInfo(userId: Long): UserInfo { … }
suspend fun getUserOrders(userId: Long): List<Order> { … }
concurrently executed
suspension
happens here
Structured Concurrency
suspend fun showUserDetails(userId: Long) {
coroutineScope {
val userInfo = async { getUserInfo(userId) }
val orders = async { getUserOrders(userId) }
combineAndBuild(userInfo.await(), orders.await())
}
}
When can a resource leakage happen?
Structured Concurrency
suspend fun showUserDetails(userId: Long) {
coroutineScope {
val userInfo = async { getUserInfo(userId) }
val orders = async { getUserOrders(userId) }
combineAndBuild(userInfo.await(), orders.await())
}
}
Exception in a coroutine results in its cancellation
1
2
3
4
Kotlin Coroutines
No restructuring of code to a different paradigm
Reuse existing language control flows
Sequential vs Concurrent execution with coroutines
Complexities of async programming that coroutines handles
Call to Action
https://kotlinlang.org/docs/reference/coroutines-overview.html
https://www.youtube.com/results?search_query=kotlin+coroutines
Give it a try on your next project
Thank You
https://praveergupta.in/
https://praveer09.github.io/

More Related Content

PDF
Kotlin Coroutines. Flow is coming
PDF
uerj201212
PDF
Introduction to Coroutines @ KotlinConf 2017
PDF
The async/await concurrency pattern in Golang
PDF
Kotlin의 코루틴은 어떻게 동작하는가
PDF
Kotlin Coroutines Reloaded
PDF
Kotlin coroutine - behind the scenes
PDF
Introduction to kotlin coroutines
Kotlin Coroutines. Flow is coming
uerj201212
Introduction to Coroutines @ KotlinConf 2017
The async/await concurrency pattern in Golang
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin Coroutines Reloaded
Kotlin coroutine - behind the scenes
Introduction to kotlin coroutines

What's hot (20)

PDF
Deep dive into Coroutines on JVM @ KotlinConf 2017
PDF
Golang Channels
PDF
Ruby to Elixir - what's great and what you might miss
PDF
Groovy ネタ NGK 忘年会2009 ライトニングトーク
PPTX
Introduction to linux day1
PDF
Elixir & Phoenix - fast, concurrent and explicit
KEY
Clojure入門
PDF
Do you Promise?
PDF
Stop Guessing and Start Measuring - Benchmarking in Practice (Lambdadays)
PDF
はじめてのGroovy
PDF
Go Concurrency
PDF
Goroutines and Channels in practice
PDF
Cooking pies with Celery
PDF
"PostgreSQL and Python" Lightning Talk @EuroPython2014
PDF
Python postgre sql a wonderful wedding
PPTX
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
PDF
Combine vs RxSwift
PDF
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
PDF
Go破壊
KEY
EventMachine for RubyFuZa 2012
Deep dive into Coroutines on JVM @ KotlinConf 2017
Golang Channels
Ruby to Elixir - what's great and what you might miss
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Introduction to linux day1
Elixir & Phoenix - fast, concurrent and explicit
Clojure入門
Do you Promise?
Stop Guessing and Start Measuring - Benchmarking in Practice (Lambdadays)
はじめてのGroovy
Go Concurrency
Goroutines and Channels in practice
Cooking pies with Celery
"PostgreSQL and Python" Lightning Talk @EuroPython2014
Python postgre sql a wonderful wedding
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
Combine vs RxSwift
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
Go破壊
EventMachine for RubyFuZa 2012
Ad

Similar to Tackling Asynchrony with Kotlin Coroutines (20)

PDF
Coroutines in Kotlin. In-depth review
PDF
Coroutines in Kotlin. UA Mobile 2017.
PDF
Current State of Coroutines
PDF
Generics and Inference
PDF
Kotlin - Coroutine
PDF
Job Queue in Golang
PPTX
Reactive Java (33rd Degree)
PDF
Dip into Coroutines - KTUG Munich 202303
PDF
Introdução à Spring Web Flux
PDF
Programação assíncrona utilizando Coroutines
PDF
Lean way write asynchronous code with Kotlin’s coroutines - Ronen Sabag, Gett
PDF
Go ahead, make my day
PDF
The Renaissance of C++
PDF
Programação Assíncrona com Kotlin Coroutines
PPTX
C sharp 8
PDF
Kotlin boost yourproductivity
PDF
Should it be routine to use coroutines?
PDF
pdx-react-observables
PDF
Finagle By Twitter Engineer @ Knoldus
PDF
Compose로 Android:Desktop 멀티플랫폼 만들기.pdf
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. UA Mobile 2017.
Current State of Coroutines
Generics and Inference
Kotlin - Coroutine
Job Queue in Golang
Reactive Java (33rd Degree)
Dip into Coroutines - KTUG Munich 202303
Introdução à Spring Web Flux
Programação assíncrona utilizando Coroutines
Lean way write asynchronous code with Kotlin’s coroutines - Ronen Sabag, Gett
Go ahead, make my day
The Renaissance of C++
Programação Assíncrona com Kotlin Coroutines
C sharp 8
Kotlin boost yourproductivity
Should it be routine to use coroutines?
pdx-react-observables
Finagle By Twitter Engineer @ Knoldus
Compose로 Android:Desktop 멀티플랫폼 만들기.pdf
Ad

More from Tech Triveni (20)

PDF
UI Dev in Big data world using open source
PDF
Why should a Java programmer shifts towards Functional Programming Paradigm
PDF
Reactive - Is it really a Magic Pill?
PDF
Let’s go reactive with JAVA
PDF
Programmatic Ad Tracking: Let the power of Reactive Microservices do talking
PDF
Let's refine your Scala Code
PDF
Supercharged imperative programming with Haskell and Functional Programming
PDF
Observability at scale with Neural Networks: A more proactive approach
PDF
Semi-Supervised Insight Generation from Petabyte Scale Text Data
PDF
Finding the best solution for Image Processing
PDF
Proximity Targeting at Scale using Big Data Platforms
PDF
Effecting Pure Change - How anything ever gets done in functional programming...
PDF
Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)
PDF
Live coding session on AI / ML using Google Tensorflow (Python) - Tanmoy Deb ...
PDF
Distributing the SMACK stack - Kubernetes VS DCOS - Sahil Sawhney (Knoldus Inc.)
PDF
Blue Pill / Red Pill : The Matrix of thousands of data streams - Himanshu Gup...
PDF
UX in Big Data Analytics - Paramjit Jolly (Guavus)
PDF
Simplified Scala Monads And Transformation - Harmeet Singh (Knoldus Inc.)
PDF
Micro Frontends Architecture - Jitendra kumawat (Guavus)
PDF
Apache CarbonData+Spark to realize data convergence and Unified high performa...
UI Dev in Big data world using open source
Why should a Java programmer shifts towards Functional Programming Paradigm
Reactive - Is it really a Magic Pill?
Let’s go reactive with JAVA
Programmatic Ad Tracking: Let the power of Reactive Microservices do talking
Let's refine your Scala Code
Supercharged imperative programming with Haskell and Functional Programming
Observability at scale with Neural Networks: A more proactive approach
Semi-Supervised Insight Generation from Petabyte Scale Text Data
Finding the best solution for Image Processing
Proximity Targeting at Scale using Big Data Platforms
Effecting Pure Change - How anything ever gets done in functional programming...
Becoming a Functional Programmer - Harit Himanshu (Nomis Solutions)
Live coding session on AI / ML using Google Tensorflow (Python) - Tanmoy Deb ...
Distributing the SMACK stack - Kubernetes VS DCOS - Sahil Sawhney (Knoldus Inc.)
Blue Pill / Red Pill : The Matrix of thousands of data streams - Himanshu Gup...
UX in Big Data Analytics - Paramjit Jolly (Guavus)
Simplified Scala Monads And Transformation - Harmeet Singh (Knoldus Inc.)
Micro Frontends Architecture - Jitendra kumawat (Guavus)
Apache CarbonData+Spark to realize data convergence and Unified high performa...

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
MYSQL Presentation for SQL database connectivity
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Digital-Transformation-Roadmap-for-Companies.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MIND Revenue Release Quarter 2 2025 Press Release
The AUB Centre for AI in Media Proposal.docx
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Network Security Unit 5.pdf for BCA BBA.
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Review of recent advances in non-invasive hemoglobin estimation
MYSQL Presentation for SQL database connectivity

Tackling Asynchrony with Kotlin Coroutines

  • 1. Tackling Asynchrony with Kotlin Coroutines Presented By: PRAVEER GUPTA
  • 2. fun getUserAddress(userId: Long): Address { … } fun getRestaurants(address: Address): List<Restaurant> { … } Sync or Async?
  • 3. Reactive approach to Async fun getUserAddress(userId: Long): Single<Address> { … } fun getRestaurants(address: Address): Single<List<Restaurant>> { … } Wrapped return types
  • 4. Kotlin Coroutine’s approach to Async suspend fun getUserAddress(userId: Long): Address { … } suspend fun getRestaurants(address: Address): List<Restaurant> { … } Suspend modifier
  • 5. Sync API Usage fun showUserRestaurants(userId: Long) { val address = getUserAddress(userId) val restaurants = getRestaurants(address) processRestaurants(restaurants) } fun getUserAddress(userId: Long): Address { … } fun getRestaurants(address: Address): List<Restaurant> { … } Sequential & blocking
  • 6. fun showUserRestaurants(userId: Long) { getUserAddress(userId) .flatMap { address -> getRestaurants(address) } .subscribe { restaurants -> processRestaurants(restaurants) } } Reactive API Usage fun getUserAddress(userId: Long): Single<Address> { … } fun getRestaurants(address: Address): Single<List<Restaurant>> { … } Chained operators & actions
  • 7. Kotlin Coroutine API Usage suspend fun showUserRestaurants(userId: Long) { val address = getUserAddress(userId) val restaurants = getRestaurants(address) processRestaurants(restaurants) } suspend fun getUserAddress(userId: Long): Address { … } suspend fun getRestaurants(address: Address): List<Restaurant> { … } Suspend modifier
  • 8. Comparison suspend fun showUserRestaurants(userId: Long) { val address = getUserAddress(userId) val restaurants = getRestaurants(address) processRestaurants(restaurants) } suspend fun getUserAddress(userId: Long): Address { … } suspend fun getRestaurants(address: Address): List<Restaurant> { … } fun showUserRestaurants(userId: Long) { val address = getUserAddress(userId) val restaurants = getRestaurants(address) processRestaurants(restaurants) } fun getUserAddress(userId: Long): Address { … } fun getRestaurants(address: Address): List<Restaurant> { … } Synchronous Asynchronous using Kotlin Coroutines
  • 9. Structure of imperative synchronous code is the same as asynchronous code (taken from KotlinConf 2018 - Exploring Coroutines in Kotlin by Venkat Subramaniam available on YouTube) Kotlin Coroutines
  • 10. Kotlin Coroutines No restructuring of code to a different paradigm Reuse existing language control flows Sequential vs Concurrent execution with coroutines Complexities of async programming that coroutines handles
  • 11. Kotlin Coroutines 101 import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(1000L) println("World!") } println("Hello") } Output: Hello World!
  • 12. import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(1000L) println("World!") } println("Hello") } Coroutine Builders Coroutine - an instance of a suspendable computation Kotlin Coroutines 101
  • 13. import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(1000L) println("World!") } println("Hello") } Suspending function suspends the execution of the coroutine Kotlin Coroutines 101
  • 14. Suspended coroutine resumes with a continuation block public interface Continuation<in T> { public val context: CoroutineContext public fun resumeWith(result: Result<T>) } import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(1000L) println("World!") } println("Hello") } Kotlin Coroutines 101
  • 15. import kotlinx.coroutines.* fun main() = runBlocking { launch { doWorld() } println("Hello") } private suspend fun doWorld() { delay(1000L) println("World!") } Suspending function is marked with a suspend modifier Kotlin Coroutines 101
  • 17. suspend fun showUserRestaurants(userId: Long) { val address = getUserAddress(userId) val restaurants = getRestaurants(address) processRestaurants(restaurants) } Reuse existing Control flows How can you make the below method resilient to failures?
  • 18. suspend fun showUserRestaurants(userId: Long) { try { val address = withTimeout(200L) { getUserAddress(userId) } val restaurants = withTimeout(300L) { getRestaurants(address) } processRestaurants(restaurants) } catch (e: TimeoutCancellationException) { // handle exception here } } Exception handling using standard try-catch block Reuse existing Control flows
  • 19. Sequential vs Concurrent suspend fun showUserDetails(userId: Long) { val userInfo = getUserInfo(userId) val orders = getUserOrders(userId) combineAndBuild(userInfo, orders) } Two independent calls to external system suspend fun getUserInfo(userId: Long): UserInfo { … } suspend fun getUserOrders(userId: Long): List<Order> { … }
  • 20. suspend fun showUserDetails(userId: Long) { val userInfo = getUserInfo(userId) val orders = getUserOrders(userId) combineAndBuild(userInfo, orders) } Sequential vs Concurrent suspend fun getUserInfo(userId: Long): UserInfo { … } suspend fun getUserOrders(userId: Long): List<Order> { … } first suspension
  • 21. Sequential vs Concurrent suspend fun getUserInfo(userId: Long): UserInfo { … } suspend fun getUserOrders(userId: Long): List<Order> { … } suspend fun showUserDetails(userId: Long) { val userInfo = getUserInfo(userId) val orders = getUserOrders(userId) combineAndBuild(userInfo, orders) } second suspension
  • 22. Sequential vs Concurrent suspend fun getUserInfo(userId: Long): UserInfo { … } suspend fun getUserOrders(userId: Long): List<Order> { … } suspend fun showUserDetails(userId: Long) { val userInfo = getUserInfo(userId) val orders = getUserOrders(userId) combineAndBuild(userInfo, orders) } final call
  • 23. Sequential vs Concurrent suspend fun showUserDetails(userId: Long) { val userInfo = getUserInfo(userId) val orders = getUserOrders(userId) combineAndBuild(userInfo, orders) } suspend fun getUserInfo(userId: Long): UserInfo { … } suspend fun getUserOrders(userId: Long): List<Order> { … } sequential execution by default
  • 24. Sequential vs Concurrent suspend fun showUserDetails(userId: Long) { coroutineScope { val userInfo = async { getUserInfo(userId) } val orders = async { getUserOrders(userId) } combineAndBuild(userInfo.await(), orders.await()) } } suspend fun getUserInfo(userId: Long): UserInfo { … } suspend fun getUserOrders(userId: Long): List<Order> { … } concurrently executed suspension happens here
  • 25. Structured Concurrency suspend fun showUserDetails(userId: Long) { coroutineScope { val userInfo = async { getUserInfo(userId) } val orders = async { getUserOrders(userId) } combineAndBuild(userInfo.await(), orders.await()) } } When can a resource leakage happen?
  • 26. Structured Concurrency suspend fun showUserDetails(userId: Long) { coroutineScope { val userInfo = async { getUserInfo(userId) } val orders = async { getUserOrders(userId) } combineAndBuild(userInfo.await(), orders.await()) } } Exception in a coroutine results in its cancellation 1 2 3 4
  • 27. Kotlin Coroutines No restructuring of code to a different paradigm Reuse existing language control flows Sequential vs Concurrent execution with coroutines Complexities of async programming that coroutines handles