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

What's hot (20)

PDF
Go Containers
jgrahamc
 
PDF
Kotlin from-scratch 3 - coroutines
Franco Lombardo
 
PDF
Javascript ES6 generators
RameshNair6
 
PDF
The Ring programming language version 1.5.2 book - Part 45 of 181
Mahmoud Samir Fayed
 
PDF
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Víctor Bolinches
 
PDF
Golang Channels
Joris Bonnefoy
 
PDF
The Ring programming language version 1.5.1 book - Part 65 of 180
Mahmoud Samir Fayed
 
PDF
Le Wagon - Javascript for Beginners
Sébastien Saunier
 
PDF
Beyond Golden Containers: Complementing Docker with Puppet
lutter
 
PDF
Goroutines and Channels in practice
Guilherme Garnier
 
PDF
Introduction to rust
mysangle
 
PDF
ES6 generators
Steven Foote
 
PDF
The Ring programming language version 1.8 book - Part 51 of 202
Mahmoud Samir Fayed
 
PDF
Go memory
jgrahamc
 
PDF
The Ring programming language version 1.10 book - Part 94 of 212
Mahmoud Samir Fayed
 
PDF
FPBrno 2018-05-22: Benchmarking in elixir
Functional Programming Brno
 
PDF
Test Driven Cocos2d
Eric Smith
 
PDF
Queue in swift
joonjhokil
 
PDF
The Ring programming language version 1.9 book - Part 56 of 210
Mahmoud Samir Fayed
 
PDF
Test driven game development silly, stupid or inspired?
Eric Smith
 
Go Containers
jgrahamc
 
Kotlin from-scratch 3 - coroutines
Franco Lombardo
 
Javascript ES6 generators
RameshNair6
 
The Ring programming language version 1.5.2 book - Part 45 of 181
Mahmoud Samir Fayed
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Víctor Bolinches
 
Golang Channels
Joris Bonnefoy
 
The Ring programming language version 1.5.1 book - Part 65 of 180
Mahmoud Samir Fayed
 
Le Wagon - Javascript for Beginners
Sébastien Saunier
 
Beyond Golden Containers: Complementing Docker with Puppet
lutter
 
Goroutines and Channels in practice
Guilherme Garnier
 
Introduction to rust
mysangle
 
ES6 generators
Steven Foote
 
The Ring programming language version 1.8 book - Part 51 of 202
Mahmoud Samir Fayed
 
Go memory
jgrahamc
 
The Ring programming language version 1.10 book - Part 94 of 212
Mahmoud Samir Fayed
 
FPBrno 2018-05-22: Benchmarking in elixir
Functional Programming Brno
 
Test Driven Cocos2d
Eric Smith
 
Queue in swift
joonjhokil
 
The Ring programming language version 1.9 book - Part 56 of 210
Mahmoud Samir Fayed
 
Test driven game development silly, stupid or inspired?
Eric Smith
 

Similar to Kotlin - Coroutine (20)

PDF
Quick Introduction to Kotlin Coroutine for Android Dev
Shuhei Shogen
 
PPTX
Coroutines talk ppt
Shahroz Khan
 
PDF
Programação assíncrona utilizando Coroutines
Diego Gonçalves Santos
 
PDF
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
tdc-globalcode
 
PDF
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
PDF
Coroutines
Sevil Güler
 
PDF
Structured concurrency with Kotlin Coroutines
Vadims Savjolovs
 
PDF
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
PDF
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
PDF
Improving app performance with Kotlin Coroutines
Hassan Abid
 
PDF
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
PDF
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 
PDF
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
PDF
Kotlin coroutine - behind the scenes
Anh Vu
 
PDF
Aplicações Assíncronas no Android com Coroutines e Jetpack
Nelson Glauber Leal
 
PDF
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 
PDF
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
PDF
droidcon Transylvania - Kotlin Coroutines
Arthur Nagy
 
PDF
Should it be routine to use coroutines?
Ion Stefan Brosteanu
 
PDF
Dive into kotlins coroutines
Freddie Wang
 
Quick Introduction to Kotlin Coroutine for Android Dev
Shuhei Shogen
 
Coroutines talk ppt
Shahroz Khan
 
Programação assíncrona utilizando Coroutines
Diego Gonçalves Santos
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
tdc-globalcode
 
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
Coroutines
Sevil Güler
 
Structured concurrency with Kotlin Coroutines
Vadims Savjolovs
 
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Improving app performance with Kotlin Coroutines
Hassan Abid
 
Introduction to Coroutines @ KotlinConf 2017
Roman Elizarov
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 
Tackling Asynchrony with Kotlin Coroutines
Tech Triveni
 
Kotlin coroutine - behind the scenes
Anh Vu
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Nelson Glauber Leal
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
droidcon Transylvania - Kotlin Coroutines
Arthur Nagy
 
Should it be routine to use coroutines?
Ion Stefan Brosteanu
 
Dive into kotlins coroutines
Freddie Wang
 
Ad

More from Sean Tsai (8)

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

Recently uploaded (20)

PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 

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