SlideShare a Scribd company logo
Quick introduction to Kotlin
Coroutine
Shuhei Shogen
What is this doc?
• Give you the basic idea of Coroutine
• Why is it needed?
• Syntax and its use case
• Coroutine in Android (only a little)
Overview of Kotlin
• Official page: https://kotlinlang.org/
• Developed by JetBrains Inc.
• Statically typed
• Latest version: 1.4.32 (as of 2021/4/13)
• https://www.slideshare.net/ShuheiShogen1/introduction-to-kotlin-
for-java-developer-168613075
Parallel processing
• A heavy process (like NW/DB access) might occupy a thread
• In case of Android, it will block the UI thread (-> ANR error)
• We need a way to process it in parallel with UI process
fun main() {
val data = fetchData() // Heavy process 1
saveData(data) // Heavy process 2
displayData(data)
}
Parallel processing is difficult
• Threading?
• Difficult to deal with many threads
• Eat a lot of memory
fun main() {
val thread = thread { // Run the block in another thread
val data = fetchData()
saveData(data)
}
thread.join() // Wait until the thread is completed
displayData(data)
}
Parallel processing is difficult
• Callback?
• Easily lead to complicated logics with deep nests (= callback hell)
// Modify it so that it will accept a callback method
fun fetchData(callback: Data -> Unit): Unit
fun saveData(data: Data, callback: Data -> Unit): Unit
fun main() {
fetchData { data -> { // Executed after fetchData is completed
saveData(data) { // Executed after saveData is completed
displayData(data)
}
}
}
}
Parallel processing is difficult
• RxKotlin?
• Too many operators...
fun main() {
fetchData()
.flatMap { data -> {
saveData(data)
data
}
.subscribe { data -> displayData(data) }
}
Parallel processing is difficult
• Coroutine
• Simple (we are using async/await syntax)
fun main() {
val deferredData = async { // "async" will start a coroutine and return a deferred object
val data = fetchData()
saveData(data)
data // Return value
}.await() // "Deferred<T>#await will wait until the target coroutine completes"
displayData(deferredData)
}
Kotlin Coroutine
• Coroutines are light-weight threads
• Suspendable/Cancellable in any part of the block
• Handy (-> Less chance of memory leak)
• Officially introduced in Kotlin 1.3
Thread 1
Coroutine v.s. Threading
Process 1
Threading
Coroutine
Process 3
IO wait IO wait
Thread 2 Process 2
Idle
Coroutine 1 Process 1 Process 3
Suspending Suspending
Coroutine 2 Process 2
IO wait Process 4
Suspending Process 4
Thread 1 Process 1 Process 2 Process 3 Process 4
Idle
Waste of resource
Efficient use of threads :)
Set up
// build.gradle (app)
repositories {
mavenCentral()
}
// In case of a normal Kotlin app
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
}
// In case of Android
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
}
Our first Coroutine
fun main() {
runBlocking { // Create a CoroutineScope and wait until all the Coroutines finish (Don't use it in production)
launch { // Run a Coroutine
println("1")
delay(1000L) // Suspend the Coroutine for 1000 ms
println("2")
}
launch { // Run a Coroutine
println("3")
}
}
}
---
1
3
2
CoroutineScope
• Scope (Block) in which a Coroutine is allowed to be run
• Initialized with CoroutineContext / by runBlocking function
fun main() {
val job = Job() // Coroutine Job
val coroutineDispatcher = Dispatcher.IO // Indicate the Coroutine will be executed in (preserved) IO threads
val coroutineContext = coroutineDispatcher + Job() // Create a CoroutineContext by combining job and dispatcher
val scope = CoroutineScope(coroutineContext) // Create a CoroutineScope from CoroutineContext
scope.launch {
println("1")
delay(1000L)
println("2")
}
scope.launch {
println("3")
}
}
async / await
• Return a Deferred<T> object that contains the result of Coroutine (v.s. launch returns a Coroutine Job)
• Useful if you want the result value of a heavy process
fun main() {
runBlocking {
val deferred1 = async { // Deferred<Int>
delay(1000L)
1
}
val deferred2 = async {// Deferred<Int>
delay(2000L)
2
}
println(deferred1.await() + deferred2.await()) // Wait until both Coroutines are completed (for 2000 ms)
}
}
---
3
Suspending function
• A function that can be suspended in the context of Coroutine
• Suspending function can be called only either in a Coroutine or in (another) suspending function
• delay() and await() are suspending functions
// Wrong
fun simulateWorkload() {
delay(1000L) // Compliration error
}
---
// Correct
suspend fun simulateWorkload() {
delay(1000L)
}
GlobalScope.launch {
simulateWorkload() // A suspending function can be called in a Coroutine
}
Test your Coroutine
• Use TestCoroutineDispatcher
class MyRepository(
private val coroutineDispatcher: CoroutineDispatcher
) {
fun fetchData(): List<Data> {
withContext(coroutineDispatcher) {
// Do heavy IO process
return dataList
}
}
}
class MyRepositoryTest {
private val testDispatcher = TestCoroutineDispatcher()
@Test
fun testFetchData() {
testDispatcher.runBlockingTest {
// Mock dependencies if needed
val repository = MyRepository(testDispatcher)
val expected = ... // Define the expected value
val actual = repository.fetchData
assertThat(expected, `is`(actual))
}
}
}
Coroutine in Android app
• AndroidX lifecycle has viewModelScope in ViewModel
• This CoroutineScope will be automatically cancelled when the ViewModel is destroyed
class MyViewModel(
private val myRepository: MyRepository,
private val coroutineDispatcher: CoroutineDispatcher = Dispatcher.Main
) : ViewModel {
fun loadData() {
viewModelScope.launch { // This scope will be cancelled when MyViewModel is destroyed (= Less chance of memory leak)
val someData = myRepository.fetchData()
// UI update
}
}
}
class MyRepository(
private val coroutineDispatcher: CoroutineDispatcher = Dispatcher.IO
)
suspend fun fetchData(): List<SomeData> {
withContext(coroutineDispatcher) { // Change CoroutineContext to change the thread to be run
// ...
}
}
}
Take away
• Corourtines can be used to handle parallel processing easily
• Android has some supports for Coroutine
Topics not covered in these slides
• Detail explanation about CoroutineScope/CoroutineContext/
CoroutineDispatcher
• Error handling in Coroutine
• Kotlin Flow and its Android support
Referrences
• Kotlin Coroutine guide
• https://kotlinlang.org/docs/coroutines-guide.html
• Kotlin coroutines on Android
• https://developer.android.com/kotlin/coroutines
• 詳解 Kotlin Coroutines
• https://zenn.dev/at_sushi_at/books/edf63219adfc31
Ad

Recommended

Loom and concurrency latest
Loom and concurrency latest
Srinivasan Raghavan
 
Introduction to Kotlin for Java developer
Introduction to Kotlin for Java developer
Shuhei Shogen
 
Fork and join framework
Fork and join framework
Minh Tran
 
Java fork join
Java fork join
Masud Hasan
 
Android kotlin coroutines
Android kotlin coroutines
Bipin Vayalu
 
Build, logging, and unit test tools
Build, logging, and unit test tools
Allan Huang
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
Roman Elizarov
 
The art of concurrent programming
The art of concurrent programming
Iskren Chernev
 
Non blocking programming and waiting
Non blocking programming and waiting
Roman Elizarov
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
Sander Mak (@Sander_Mak)
 
Introduction to TPL
Introduction to TPL
Gyuwon Yi
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
Peter Antman
 
Ceylon/Java interop by Tako Schotanus
Ceylon/Java interop by Tako Schotanus
UnFroMage
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
Sander Mak (@Sander_Mak)
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
Feihong Hsu
 
Java Performance Tuning
Java Performance Tuning
Minh Hoang
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
Ivan Krylov
 
What to expect from Java 9
What to expect from Java 9
Ivan Krylov
 
Find the bottleneck of your system
Find the bottleneck of your system
Jian-Hong Pan
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
Java concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
Building GUI App with Electron and Lisp
Building GUI App with Electron and Lisp
fukamachi
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
Kazuho Oku
 
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Jian-Hong Pan
 
De Java 8 a Java 17
De Java 8 a Java 17
Víctor Leonel Orozco López
 
Not yet reactive but asyncronous mvc
Not yet reactive but asyncronous mvc
Dmitry Aleksandrov
 
HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009
jarfield
 
Fork Join
Fork Join
Dmitry Buzdin
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
Hassan Abid
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
Franco Lombardo
 

More Related Content

What's hot (20)

Non blocking programming and waiting
Non blocking programming and waiting
Roman Elizarov
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
Sander Mak (@Sander_Mak)
 
Introduction to TPL
Introduction to TPL
Gyuwon Yi
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
Peter Antman
 
Ceylon/Java interop by Tako Schotanus
Ceylon/Java interop by Tako Schotanus
UnFroMage
 
Fork Join (BeJUG 2012)
Fork Join (BeJUG 2012)
Sander Mak (@Sander_Mak)
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
Feihong Hsu
 
Java Performance Tuning
Java Performance Tuning
Minh Hoang
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
Ivan Krylov
 
What to expect from Java 9
What to expect from Java 9
Ivan Krylov
 
Find the bottleneck of your system
Find the bottleneck of your system
Jian-Hong Pan
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
Java concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
Building GUI App with Electron and Lisp
Building GUI App with Electron and Lisp
fukamachi
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
Kazuho Oku
 
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Jian-Hong Pan
 
De Java 8 a Java 17
De Java 8 a Java 17
Víctor Leonel Orozco López
 
Not yet reactive but asyncronous mvc
Not yet reactive but asyncronous mvc
Dmitry Aleksandrov
 
HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009
jarfield
 
Fork Join
Fork Join
Dmitry Buzdin
 
Non blocking programming and waiting
Non blocking programming and waiting
Roman Elizarov
 
Introduction to TPL
Introduction to TPL
Gyuwon Yi
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
Peter Antman
 
Ceylon/Java interop by Tako Schotanus
Ceylon/Java interop by Tako Schotanus
UnFroMage
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
Feihong Hsu
 
Java Performance Tuning
Java Performance Tuning
Minh Hoang
 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
Ivan Krylov
 
What to expect from Java 9
What to expect from Java 9
Ivan Krylov
 
Find the bottleneck of your system
Find the bottleneck of your system
Jian-Hong Pan
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
Java concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
Building GUI App with Electron and Lisp
Building GUI App with Electron and Lisp
fukamachi
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
Kazuho Oku
 
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Jian-Hong Pan
 
Not yet reactive but asyncronous mvc
Not yet reactive but asyncronous mvc
Dmitry Aleksandrov
 
HornetQ Presentation On JBoss World 2009
HornetQ Presentation On JBoss World 2009
jarfield
 

Similar to Quick Introduction to Kotlin Coroutine for Android Dev (20)

Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
Hassan Abid
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
Franco Lombardo
 
Kotlin - Coroutine
Kotlin - Coroutine
Sean Tsai
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
Introduction to kotlin coroutines
Introduction to kotlin coroutines
NAVER Engineering
 
Coroutines talk ppt
Coroutines talk ppt
Shahroz Khan
 
Should it be routine to use coroutines?
Should it be routine to use coroutines?
Ion Stefan Brosteanu
 
Kotlin Coroutines - the new async
Kotlin Coroutines - the new async
Bartłomiej Osmałek
 
Coroutines
Coroutines
Sevil Güler
 
Exploring Kotlin
Exploring Kotlin
Atiq Ur Rehman
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Coroutines in Kotlin
Coroutines in Kotlin
Alexey Soshin
 
Tackling Asynchrony with Kotlin Coroutines
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin Coroutines
Vadims Savjolovs
 
Asynchronous Programming in Kotlin with Coroutines
Asynchronous Programming in Kotlin with Coroutines
Tobias Schürg
 
Current State of Coroutines
Current State of Coroutines
Guido Pio Mariotti
 
Coroutines in Kotlin
Coroutines in Kotlin
Dmytro Zaitsev
 
2019-01-29 - Demystifying Kotlin Coroutines
2019-01-29 - Demystifying Kotlin Coroutines
Eamonn Boyle
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a tree
Kai Koenig
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
Hassan Abid
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
Franco Lombardo
 
Kotlin - Coroutine
Kotlin - Coroutine
Sean Tsai
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
Introduction to kotlin coroutines
Introduction to kotlin coroutines
NAVER Engineering
 
Coroutines talk ppt
Coroutines talk ppt
Shahroz Khan
 
Should it be routine to use coroutines?
Should it be routine to use coroutines?
Ion Stefan Brosteanu
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Coroutines in Kotlin
Coroutines in Kotlin
Alexey Soshin
 
Tackling Asynchrony with Kotlin Coroutines
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin Coroutines
Vadims Savjolovs
 
Asynchronous Programming in Kotlin with Coroutines
Asynchronous Programming in Kotlin with Coroutines
Tobias Schürg
 
2019-01-29 - Demystifying Kotlin Coroutines
2019-01-29 - Demystifying Kotlin Coroutines
Eamonn Boyle
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a tree
Kai Koenig
 
Ad

Recently uploaded (20)

Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
Building Geospatial Data Warehouse for GIS by GIS with FME
Building Geospatial Data Warehouse for GIS by GIS with FME
Safe Software
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Ad

Quick Introduction to Kotlin Coroutine for Android Dev

  • 1. Quick introduction to Kotlin Coroutine Shuhei Shogen
  • 2. What is this doc? • Give you the basic idea of Coroutine • Why is it needed? • Syntax and its use case • Coroutine in Android (only a little)
  • 3. Overview of Kotlin • Official page: https://kotlinlang.org/ • Developed by JetBrains Inc. • Statically typed • Latest version: 1.4.32 (as of 2021/4/13) • https://www.slideshare.net/ShuheiShogen1/introduction-to-kotlin- for-java-developer-168613075
  • 4. Parallel processing • A heavy process (like NW/DB access) might occupy a thread • In case of Android, it will block the UI thread (-> ANR error) • We need a way to process it in parallel with UI process fun main() { val data = fetchData() // Heavy process 1 saveData(data) // Heavy process 2 displayData(data) }
  • 5. Parallel processing is difficult • Threading? • Difficult to deal with many threads • Eat a lot of memory fun main() { val thread = thread { // Run the block in another thread val data = fetchData() saveData(data) } thread.join() // Wait until the thread is completed displayData(data) }
  • 6. Parallel processing is difficult • Callback? • Easily lead to complicated logics with deep nests (= callback hell) // Modify it so that it will accept a callback method fun fetchData(callback: Data -> Unit): Unit fun saveData(data: Data, callback: Data -> Unit): Unit fun main() { fetchData { data -> { // Executed after fetchData is completed saveData(data) { // Executed after saveData is completed displayData(data) } } } }
  • 7. Parallel processing is difficult • RxKotlin? • Too many operators... fun main() { fetchData() .flatMap { data -> { saveData(data) data } .subscribe { data -> displayData(data) } }
  • 8. Parallel processing is difficult • Coroutine • Simple (we are using async/await syntax) fun main() { val deferredData = async { // "async" will start a coroutine and return a deferred object val data = fetchData() saveData(data) data // Return value }.await() // "Deferred<T>#await will wait until the target coroutine completes" displayData(deferredData) }
  • 9. Kotlin Coroutine • Coroutines are light-weight threads • Suspendable/Cancellable in any part of the block • Handy (-> Less chance of memory leak) • Officially introduced in Kotlin 1.3
  • 10. Thread 1 Coroutine v.s. Threading Process 1 Threading Coroutine Process 3 IO wait IO wait Thread 2 Process 2 Idle Coroutine 1 Process 1 Process 3 Suspending Suspending Coroutine 2 Process 2 IO wait Process 4 Suspending Process 4 Thread 1 Process 1 Process 2 Process 3 Process 4 Idle Waste of resource Efficient use of threads :)
  • 11. Set up // build.gradle (app) repositories { mavenCentral() } // In case of a normal Kotlin app dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3' testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3' } // In case of Android dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0' testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3' }
  • 12. Our first Coroutine fun main() { runBlocking { // Create a CoroutineScope and wait until all the Coroutines finish (Don't use it in production) launch { // Run a Coroutine println("1") delay(1000L) // Suspend the Coroutine for 1000 ms println("2") } launch { // Run a Coroutine println("3") } } } --- 1 3 2
  • 13. CoroutineScope • Scope (Block) in which a Coroutine is allowed to be run • Initialized with CoroutineContext / by runBlocking function fun main() { val job = Job() // Coroutine Job val coroutineDispatcher = Dispatcher.IO // Indicate the Coroutine will be executed in (preserved) IO threads val coroutineContext = coroutineDispatcher + Job() // Create a CoroutineContext by combining job and dispatcher val scope = CoroutineScope(coroutineContext) // Create a CoroutineScope from CoroutineContext scope.launch { println("1") delay(1000L) println("2") } scope.launch { println("3") } }
  • 14. async / await • Return a Deferred<T> object that contains the result of Coroutine (v.s. launch returns a Coroutine Job) • Useful if you want the result value of a heavy process fun main() { runBlocking { val deferred1 = async { // Deferred<Int> delay(1000L) 1 } val deferred2 = async {// Deferred<Int> delay(2000L) 2 } println(deferred1.await() + deferred2.await()) // Wait until both Coroutines are completed (for 2000 ms) } } --- 3
  • 15. Suspending function • A function that can be suspended in the context of Coroutine • Suspending function can be called only either in a Coroutine or in (another) suspending function • delay() and await() are suspending functions // Wrong fun simulateWorkload() { delay(1000L) // Compliration error } --- // Correct suspend fun simulateWorkload() { delay(1000L) } GlobalScope.launch { simulateWorkload() // A suspending function can be called in a Coroutine }
  • 16. Test your Coroutine • Use TestCoroutineDispatcher class MyRepository( private val coroutineDispatcher: CoroutineDispatcher ) { fun fetchData(): List<Data> { withContext(coroutineDispatcher) { // Do heavy IO process return dataList } } } class MyRepositoryTest { private val testDispatcher = TestCoroutineDispatcher() @Test fun testFetchData() { testDispatcher.runBlockingTest { // Mock dependencies if needed val repository = MyRepository(testDispatcher) val expected = ... // Define the expected value val actual = repository.fetchData assertThat(expected, `is`(actual)) } } }
  • 17. Coroutine in Android app • AndroidX lifecycle has viewModelScope in ViewModel • This CoroutineScope will be automatically cancelled when the ViewModel is destroyed class MyViewModel( private val myRepository: MyRepository, private val coroutineDispatcher: CoroutineDispatcher = Dispatcher.Main ) : ViewModel { fun loadData() { viewModelScope.launch { // This scope will be cancelled when MyViewModel is destroyed (= Less chance of memory leak) val someData = myRepository.fetchData() // UI update } } } class MyRepository( private val coroutineDispatcher: CoroutineDispatcher = Dispatcher.IO ) suspend fun fetchData(): List<SomeData> { withContext(coroutineDispatcher) { // Change CoroutineContext to change the thread to be run // ... } } }
  • 18. Take away • Corourtines can be used to handle parallel processing easily • Android has some supports for Coroutine
  • 19. Topics not covered in these slides • Detail explanation about CoroutineScope/CoroutineContext/ CoroutineDispatcher • Error handling in Coroutine • Kotlin Flow and its Android support
  • 20. Referrences • Kotlin Coroutine guide • https://kotlinlang.org/docs/coroutines-guide.html • Kotlin coroutines on Android • https://developer.android.com/kotlin/coroutines • 詳解 Kotlin Coroutines • https://zenn.dev/at_sushi_at/books/edf63219adfc31