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

PDF
Loom and concurrency latest
PDF
Introduction to Kotlin for Java developer
PPTX
Fork and join framework
PDF
Java fork join
PPTX
Android kotlin coroutines
PPTX
Build, logging, and unit test tools
PDF
Wait for your fortune without Blocking!
PDF
The art of concurrent programming
Loom and concurrency latest
Introduction to Kotlin for Java developer
Fork and join framework
Java fork join
Android kotlin coroutines
Build, logging, and unit test tools
Wait for your fortune without Blocking!
The art of concurrent programming

What's hot (20)

PPTX
Non blocking programming and waiting
KEY
Fork/Join for Fun and Profit!
PPTX
Introduction to TPL
ODP
Threads and concurrency in Java 1.5
PDF
Ceylon/Java interop by Tako Schotanus
PDF
Fork Join (BeJUG 2012)
PDF
Asynchronous I/O in Python 3
PPT
Java Performance Tuning
PDF
Code lifecycle in the jvm - TopConf Linz
PDF
What to expect from Java 9
PDF
Find the bottleneck of your system
PDF
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
PPTX
Java concurrency in practice
PDF
Building GUI App with Electron and Lisp
PPTX
HTTP::Parser::XS - writing a fast & secure XS module
PDF
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
PDF
De Java 8 a Java 17
PPTX
Not yet reactive but asyncronous mvc
ODP
HornetQ Presentation On JBoss World 2009
PPTX
Fork Join
Non blocking programming and waiting
Fork/Join for Fun and Profit!
Introduction to TPL
Threads and concurrency in Java 1.5
Ceylon/Java interop by Tako Schotanus
Fork Join (BeJUG 2012)
Asynchronous I/O in Python 3
Java Performance Tuning
Code lifecycle in the jvm - TopConf Linz
What to expect from Java 9
Find the bottleneck of your system
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
Java concurrency in practice
Building GUI App with Electron and Lisp
HTTP::Parser::XS - writing a fast & secure XS module
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
De Java 8 a Java 17
Not yet reactive but asyncronous mvc
HornetQ Presentation On JBoss World 2009
Fork Join
Ad

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

PDF
Structured concurrency with Kotlin Coroutines
PPTX
.NET Multithreading/Multitasking
PDF
Asynchronous programming intro
PDF
Kotlin coroutine - the next step for RxJava developer?
PDF
kotlin coroutine, What’s asynchronous programming What’s coroutine How Kotlin...
ODP
Concurrent Programming in Java
PDF
Demystifying the Go Scheduler
PDF
Kotlin Coroutines and Android sitting in a tree
PPTX
Async and parallel patterns and application design - TechDays2013 NL
PDF
Let's Talk Locks!
PDF
Coroutines for Kotlin Multiplatform in Practise
PDF
New Features Of JDK 7
ODP
Java Concurrency, Memory Model, and Trends
PPTX
Java On CRaC
PDF
Blocks & GCD
PDF
TorqueBox at GNUnify 2012
PDF
Improving app performance with Kotlin Coroutines
PDF
Live Container Migration: OpenStack Summit Barcelona 2016
PPTX
CoreOS Intro
PDF
node.js 실무 - node js in practice by Jesang Yoon
Structured concurrency with Kotlin Coroutines
.NET Multithreading/Multitasking
Asynchronous programming intro
Kotlin coroutine - the next step for RxJava developer?
kotlin coroutine, What’s asynchronous programming What’s coroutine How Kotlin...
Concurrent Programming in Java
Demystifying the Go Scheduler
Kotlin Coroutines and Android sitting in a tree
Async and parallel patterns and application design - TechDays2013 NL
Let's Talk Locks!
Coroutines for Kotlin Multiplatform in Practise
New Features Of JDK 7
Java Concurrency, Memory Model, and Trends
Java On CRaC
Blocks & GCD
TorqueBox at GNUnify 2012
Improving app performance with Kotlin Coroutines
Live Container Migration: OpenStack Summit Barcelona 2016
CoreOS Intro
node.js 실무 - node js in practice by Jesang Yoon
Ad

Recently uploaded (20)

PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Online Work Permit System for Fast Permit Processing
PDF
AI in Product Development-omnex systems
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
history of c programming in notes for students .pptx
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
top salesforce developer skills in 2025.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
ai tools demonstartion for schools and inter college
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
System and Network Administration Chapter 2
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Online Work Permit System for Fast Permit Processing
AI in Product Development-omnex systems
ISO 45001 Occupational Health and Safety Management System
L1 - Introduction to python Backend.pptx
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Design an Analysis of Algorithms II-SECS-1021-03
history of c programming in notes for students .pptx
Which alternative to Crystal Reports is best for small or large businesses.pdf
How Creative Agencies Leverage Project Management Software.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
CHAPTER 2 - PM Management and IT Context
top salesforce developer skills in 2025.pdf
Design an Analysis of Algorithms I-SECS-1021-03
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
ai tools demonstartion for schools and inter college
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
System and Network Administration Chapter 2

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