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

More Related Content

What's hot (20)

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

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

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

Recently uploaded (20)

PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Import Data Form Excel to Tally Services
Tally xperts
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
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