SlideShare a Scribd company logo
Kotlin - Coroutine
Kotlin - Coroutine
Kotlin - Coroutine
Like light-weight threads.
fun main() = runBlocking {
repeat(100_000) { // launch a lot of coroutines
thread {
delay(1000L)
print(".")
}
}
}
fun main() = runBlocking {
repeat(100_000) { // launch a lot of coroutines
launch {
delay(1000L)
print(".")
}
}
}
fun postItem(item: Item) {
requestTokenAsync { token ->
createPostAsync(token, item) { post ->
processPost(post)
}
}
}
Rx/Futures/Promises to the rescue
Basic Sample with Android
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
GlobalScope.launch (Dispatchers.Main){
toast("Hello world!!!")
delay(10, TimeUnit.SECONDS)
textView.text = "Hello!! Android Taipei!!"
}
}
}
GlobalScope.launch
Samples with Retrofit
interface RetrofitService {
@GET("/posts")
fun getPosts(): Call<List<Post>>
}
Declaring an Interface (Call)
interface RetrofitService {
@GET("/posts")
fun getPosts(): Deferred<<List<Post>>
}
Declaring an Interface (Coroutine)
object RetrofitFactory {
const val BASE_URL = "https://sample.com"
fun makeRetrofitService(): RetrofitService {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build().create(RetrofitService::class.java)
}
}
Building Retrofit Service
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val service = RetrofitFactory.makeRetrofitService()
GlobalScope.launch(Dispatchers.Main) {
val request = service.getPosts()
try {
val response = request.await()
// Do something with the response.
} catch (e: HttpException) {
toast(e.code())
} catch (e: Throwable) {
toast("Ooops: Something else went wrong")
}
}
}
Bringing it all together
Kotlin - Coroutine
Kotlin - Coroutine
fun main() {
GlobalScope.launch {
delay(1000L)
println("World!")
}
println("Hello,")
Thread.sleep(2000L)
}
Kotlin - Coroutine
public interface CoroutineScope {
/**
* Context of this scope.
*/
public val coroutineContext: CoroutineContext
}
public object GlobalScope : CoroutineScope {
/**
* Returns [EmptyCoroutineContext].
*/
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
}
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
....
}
suspend fun delay(timeMillis: Long): Unit (source)
Delays coroutine for a given time without blocking a thread and
resumes it after a specified time. This suspending function is
cancellable.
Kotlin - Coroutine
Declare functions with their parameters and
return values.
• (Int) -> String
• () -> String
• (Int, Int) -> String
• () -> () -> String
var print: (Int) -> String
• var printHello: () -> String
• Var printNumbers: (Int, Int) -> String
suspend () -> Unit
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
....
}
Suspending functions can be used inside coroutines just like regular
functions, but their additional feature is that they can, in turn, use other
suspending functions.
Does something long & waits for it to complete without blocking.
fun main() = runBlocking<Unit> {
GlobalScope.launch {
delay(1000L)
println("World!")
}
println("Hello,")
delay(2000L)
}
fun main() = runBlocking {
val job = GlobalScope.launch {
delay(1000L)
println("World!")
}
println("Hello,")
job.join()
}
Structured concurrency
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
Kotlin - Coroutine
fun main() = runBlocking {
launch {
printWorld()
}
println("Hello,")
}
private suspend fun printWorld() {
delay(1000L)
println("World!")
}
Kotlin - Coroutine
• JVM Options: -Dkotlinx.coroutines.debug
• Get thread name: Thread.currentThread().name
fun main() = runBlocking<Unit> {
val a = async {
log("I'm computing a piece of the answer")
6
}
val b = async {
log("I'm computing another piece of the answer")
7
}
log("The answer is ${a.await() * b.await()}")
}
[main @coroutine#2] I'm computing a piece of the answer
[main @coroutine#3] I'm computing another piece of the answer
[main @coroutine#1] The answer is 42
Kotlin - Coroutine
•
•
•
•
•
•
Kotlin - Coroutine
Sequential by default
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = doSomethingUsefulOne()
val two = doSomethingUsefulTwo()
println("The answer is ${one + two}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): Int {
delay(1000L) // pretend we are doing something useful here
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // pretend we are doing something useful here, too
return 29
}
Sequential by default
The answer is 42
Completed in 2010 ms
•
•
public fun <T> CoroutineScope.async(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T> {
....
}
public fun CoroutineScope.launch(
context: CoroutineContext =
EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
....
}
Concurrent using async
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): Int {
delay(1000L) // pretend we are doing something useful here
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // pretend we are doing something useful here
return 29
}
Kotlin - Coroutine
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job {
....
}
•
•
•
•
fun main() = runBlocking<Unit> {
launch {
println("main runBlocking : I'm working in thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Unconfined) {
println("Unconfined : I'm working in thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Default) { // will get dispatched to DefaultDispatcher
println("Default : I'm working in thread ${Thread.currentThread().name}")
}
launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread
println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
}
}
Unconfined : I'm working in thread main @coroutine#3
Default : I'm working in thread DefaultDispatcher-worker-1 @coroutine#4
newSingleThreadContext: I'm working in thread MyOwnThread @coroutine#5
main runBlocking : I'm working in thread main @coroutine#2
•
•
•
•
•
•
•
Kotlin - Coroutine
Kotlin - Coroutine
Kotlin - Coroutine
Kotlin - Coroutine

More Related Content

PDF
Kotlin Coroutines. Flow is coming
PDF
Introduction to kotlin coroutines
KEY
Clojure入門
PDF
The Ring programming language version 1.5.1 book - Part 44 of 180
PDF
Kotlin Coroutines - the new async
PDF
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
PPTX
Python queue solution with asyncio and kafka
PPTX
Meetup Javascript for beginner
Kotlin Coroutines. Flow is coming
Introduction to kotlin coroutines
Clojure入門
The Ring programming language version 1.5.1 book - Part 44 of 180
Kotlin Coroutines - the new async
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
Python queue solution with asyncio and kafka
Meetup Javascript for beginner

What's hot (20)

PDF
Go Containers
PDF
Kotlin from-scratch 3 - coroutines
PDF
Javascript ES6 generators
PDF
The Ring programming language version 1.5.2 book - Part 45 of 181
PDF
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
PDF
Golang Channels
PDF
The Ring programming language version 1.5.1 book - Part 65 of 180
PDF
Le Wagon - Javascript for Beginners
PDF
Beyond Golden Containers: Complementing Docker with Puppet
PDF
Goroutines and Channels in practice
PDF
Introduction to rust
PDF
ES6 generators
PDF
The Ring programming language version 1.8 book - Part 51 of 202
PDF
Go memory
PDF
The Ring programming language version 1.10 book - Part 94 of 212
PDF
FPBrno 2018-05-22: Benchmarking in elixir
PDF
Test Driven Cocos2d
PDF
Queue in swift
PDF
The Ring programming language version 1.9 book - Part 56 of 210
PDF
Test driven game development silly, stupid or inspired?
Go Containers
Kotlin from-scratch 3 - coroutines
Javascript ES6 generators
The Ring programming language version 1.5.2 book - Part 45 of 181
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Golang Channels
The Ring programming language version 1.5.1 book - Part 65 of 180
Le Wagon - Javascript for Beginners
Beyond Golden Containers: Complementing Docker with Puppet
Goroutines and Channels in practice
Introduction to rust
ES6 generators
The Ring programming language version 1.8 book - Part 51 of 202
Go memory
The Ring programming language version 1.10 book - Part 94 of 212
FPBrno 2018-05-22: Benchmarking in elixir
Test Driven Cocos2d
Queue in swift
The Ring programming language version 1.9 book - Part 56 of 210
Test driven game development silly, stupid or inspired?
Ad

Similar to Kotlin - Coroutine (20)

PDF
Kotlin coroutine - the next step for RxJava developer?
PDF
Current State of Coroutines
PDF
droidcon Transylvania - Kotlin Coroutines
PDF
Kotlin for android developers whats new
PDF
Kotlin Generation
PPTX
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
PDF
Aplicações assíncronas no Android com Coroutines & Jetpack
PDF
Dive into kotlins coroutines
PDF
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
PDF
Programação assíncrona utilizando Coroutines
PDF
Aplicações Assíncronas no Android com Coroutines e Jetpack
PPTX
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
PDF
Aplicações assíncronas no Android com
Coroutines & Jetpack
PDF
Aplicações assíncronas no Android com
Coroutines & Jetpack
PDF
Compose로 Android:Desktop 멀티플랫폼 만들기.pdf
PPT
Thread
PDF
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
PPT
Orsiso
PDF
What can be done with Java, but should better be done with Erlang (@pavlobaron)
PPTX
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Kotlin coroutine - the next step for RxJava developer?
Current State of Coroutines
droidcon Transylvania - Kotlin Coroutines
Kotlin for android developers whats new
Kotlin Generation
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Aplicações assíncronas no Android com Coroutines & Jetpack
Dive into kotlins coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
Programação assíncrona utilizando Coroutines
Aplicações Assíncronas no Android com Coroutines e Jetpack
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
Compose로 Android:Desktop 멀티플랫폼 만들기.pdf
Thread
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Orsiso
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Ad

More from Sean Tsai (8)

PDF
What new in android studio 2.2
PDF
Effective Objective-C 2.0 (Item 1 - 7)
PDF
Design pattern - Iterator, Mediator and Memento
PDF
Android testing
PDF
Extensible Messaging and Presence Protocol (XMPP)
PDF
Introduction of Google Tag Manager
PDF
Google analytics
PDF
Dependency injection with koin
What new in android studio 2.2
Effective Objective-C 2.0 (Item 1 - 7)
Design pattern - Iterator, Mediator and Memento
Android testing
Extensible Messaging and Presence Protocol (XMPP)
Introduction of Google Tag Manager
Google analytics
Dependency injection with koin

Recently uploaded (20)

PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
System and Network Administration Chapter 2
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
top salesforce developer skills in 2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
assetexplorer- product-overview - presentation
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Designing Intelligence for the Shop Floor.pdf
PPTX
Introduction to Artificial Intelligence
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Digital Strategies for Manufacturing Companies
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Wondershare Filmora 15 Crack With Activation Key [2025
PTS Company Brochure 2025 (1).pdf.......
Computer Software and OS of computer science of grade 11.pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
System and Network Administration Chapter 2
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
wealthsignaloriginal-com-DS-text-... (1).pdf
top salesforce developer skills in 2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
assetexplorer- product-overview - presentation
Odoo Companies in India – Driving Business Transformation.pdf
Designing Intelligence for the Shop Floor.pdf
Introduction to Artificial Intelligence
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
How to Choose the Right IT Partner for Your Business in Malaysia
Digital Strategies for Manufacturing Companies
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...

Kotlin - Coroutine

  • 5. fun main() = runBlocking { repeat(100_000) { // launch a lot of coroutines thread { delay(1000L) print(".") } } }
  • 6. fun main() = runBlocking { repeat(100_000) { // launch a lot of coroutines launch { delay(1000L) print(".") } } }
  • 7. fun postItem(item: Item) { requestTokenAsync { token -> createPostAsync(token, item) { post -> processPost(post) } } }
  • 10. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) GlobalScope.launch (Dispatchers.Main){ toast("Hello world!!!") delay(10, TimeUnit.SECONDS) textView.text = "Hello!! Android Taipei!!" } } } GlobalScope.launch
  • 12. interface RetrofitService { @GET("/posts") fun getPosts(): Call<List<Post>> } Declaring an Interface (Call)
  • 13. interface RetrofitService { @GET("/posts") fun getPosts(): Deferred<<List<Post>> } Declaring an Interface (Coroutine)
  • 14. object RetrofitFactory { const val BASE_URL = "https://sample.com" fun makeRetrofitService(): RetrofitService { return Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build().create(RetrofitService::class.java) } } Building Retrofit Service
  • 15. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val service = RetrofitFactory.makeRetrofitService() GlobalScope.launch(Dispatchers.Main) { val request = service.getPosts() try { val response = request.await() // Do something with the response. } catch (e: HttpException) { toast(e.code()) } catch (e: Throwable) { toast("Ooops: Something else went wrong") } } } Bringing it all together
  • 18. fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") Thread.sleep(2000L) }
  • 20. public interface CoroutineScope { /** * Context of this scope. */ public val coroutineContext: CoroutineContext }
  • 21. public object GlobalScope : CoroutineScope { /** * Returns [EmptyCoroutineContext]. */ override val coroutineContext: CoroutineContext get() = EmptyCoroutineContext }
  • 22. public fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { .... }
  • 23. suspend fun delay(timeMillis: Long): Unit (source) Delays coroutine for a given time without blocking a thread and resumes it after a specified time. This suspending function is cancellable.
  • 25. Declare functions with their parameters and return values. • (Int) -> String • () -> String • (Int, Int) -> String • () -> () -> String
  • 26. var print: (Int) -> String • var printHello: () -> String • Var printNumbers: (Int, Int) -> String
  • 28. public fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { .... }
  • 29. Suspending functions can be used inside coroutines just like regular functions, but their additional feature is that they can, in turn, use other suspending functions.
  • 30. Does something long & waits for it to complete without blocking.
  • 31. fun main() = runBlocking<Unit> { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") delay(2000L) }
  • 32. fun main() = runBlocking { val job = GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") job.join() }
  • 33. Structured concurrency fun main() = runBlocking { launch { delay(1000L) println("World!") } println("Hello,") }
  • 35. fun main() = runBlocking { launch { printWorld() } println("Hello,") } private suspend fun printWorld() { delay(1000L) println("World!") }
  • 37. • JVM Options: -Dkotlinx.coroutines.debug • Get thread name: Thread.currentThread().name
  • 38. fun main() = runBlocking<Unit> { val a = async { log("I'm computing a piece of the answer") 6 } val b = async { log("I'm computing another piece of the answer") 7 } log("The answer is ${a.await() * b.await()}") }
  • 39. [main @coroutine#2] I'm computing a piece of the answer [main @coroutine#3] I'm computing another piece of the answer [main @coroutine#1] The answer is 42
  • 43. Sequential by default fun main() = runBlocking<Unit> { val time = measureTimeMillis { val one = doSomethingUsefulOne() val two = doSomethingUsefulTwo() println("The answer is ${one + two}") } println("Completed in $time ms") } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // pretend we are doing something useful here return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // pretend we are doing something useful here, too return 29 }
  • 44. Sequential by default The answer is 42 Completed in 2010 ms
  • 46. public fun <T> CoroutineScope.async( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T ): Deferred<T> { .... } public fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { .... }
  • 47. Concurrent using async fun main() = runBlocking<Unit> { val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } println("The answer is ${one.await() + two.await()}") } println("Completed in $time ms") } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // pretend we are doing something useful here return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // pretend we are doing something useful here return 29 }
  • 49. public fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { .... }
  • 51. fun main() = runBlocking<Unit> { launch { println("main runBlocking : I'm working in thread ${Thread.currentThread().name}") } launch(Dispatchers.Unconfined) { println("Unconfined : I'm working in thread ${Thread.currentThread().name}") } launch(Dispatchers.Default) { // will get dispatched to DefaultDispatcher println("Default : I'm working in thread ${Thread.currentThread().name}") } launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}") } }
  • 52. Unconfined : I'm working in thread main @coroutine#3 Default : I'm working in thread DefaultDispatcher-worker-1 @coroutine#4 newSingleThreadContext: I'm working in thread MyOwnThread @coroutine#5 main runBlocking : I'm working in thread main @coroutine#2