SlideShare a Scribd company logo
Speaker.
Kotlin
? 101
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
fun fetchUserDetail(id: String) {
val token = auth()
val user = getUser(token, id)
updateUserData(user)
}
Waaaaa~~it 😵 😵
fun fetchUserDetail(id: String) {
auth {
token -> getUser(token) {
updateUserData(it)
}
}
}
suspend fun fetchUserDetail(id: String) {
val token = auth()
val user = getUser(token, id)
updateUserData(user)
}
suspend
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
fun plusOne(initial: Int) : Int {
val ONE = 1
var result = initial
result += ONE
return result
}
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
public interface Continuation<in T> {
}
public val context: CoroutineContext
public fun resume(value: T)
public fun resumeWithException(exception: Throwable)
suspend fun fetchUserDetail(id: String) {
val token = auth()
val user = getUser(token, id)
updateUserData(user) }
}
suspend fun fetchUserDetail(id: String) {
// ...
switch (label) {
case 0:
val token = auth()
case 1:
val user = getUser(token, id)
case 2:
updateUserData(user)
}
}
fun fetchUserDetail(id: String) {
// ...
switch (label) {
case 0:
val token = auth()
case 1:
val user = getUser(token, id)
case 2:
updateUserData(user)
}
}
fun fetchUserDetail(id: String, cont: Continuation) {
switch ( label) {
case 0:
auth( )
case 1:
getUser(token, id )
case 2:
…
}
}
val sm = object : CoroutineImpl { ... }
sm.
sm
, sm
fun fetchUserDetail(id: String, cont: Contiunation) {
val sm = object : CoroutineImpl { ... }
switch (sm.label) {
case 0:
auth(sm)
case 1:
getUser(token, id, sm)
case 2:
…
}
}
fun fetchUserDetail(id: String, cont: Contiunation) {
val sm = object : CoroutineImpl { ... }
switch (sm.label) {
case 0:
sm.id = id
sm.label = 1
auth(sm)
…
}
}
fun fetchUserDetail(id: String, cont: Contiunation) {
val sm = object : CoroutineImpl { ... }
switch (sm.label) {
…
case 1:
val id = sm.id
val token = sm.result as String
sm.label = 2
getUser(token, id, sm)
…
}
fun fetchUserDetail(id: String, cont: Contiunation) {
val sm = object : CoroutineImpl {
fun resume(...) {
fetchUserDetail(null, this)
}
}
switch (sm.label) {
case 0:
…
}
}
fun fetchUserDetail(id: String, cont: Contiunation) {
val sm = cont as? ThisSM ?: object : CoroutineImpl {
fun resume(...) {
fetchUserDetail(null, this)
}
}
switch (sm.label) {
case 0:
…
}
}
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
public interface Continuation<in T> {
}
public val context: CoroutineContext
public fun resume(value: T)
public fun resumeWithException(exception: Throwable)
Kotlin의 코루틴은 어떻게 동작하는가
fun updateUserDetail(id: String) =
launch(UI) {
val token = auth()
val user = getUser(token, id)
updateUserDataOntoUI(user)
}
Kotlin의 코루틴은 어떻게 동작하는가
class DispatchedContinuation<in T> (
val dispatcher: CoroutineDispatcher,
val continuation: Continuation<T>
) : Continuation<T> by continuation {
override fun resume(value: T) {
dispatcher.dispatch(context, DispatchTask(...))
}
...
}
fun launchOnUiThread() {
launch(UI) {
delay(1000L)
...
}
}
/**
* Dispatches execution onto Android main UI thread
* and provides native [delay][Delay.delay] support.
*/
val UI =
HandlerContext(Handler(Looper.getMainLooper()), "UI")
fun main(args: Array<String>) = runBlocking<Unit> {
val jobs = arrayListOf<Job>()
jobs += launch(Unconfined) {
println("'Unconfined': I'm working in thread ${Thread.currentThread().name}")
}
jobs += launch(coroutineContext) {
println("'coroutineContext': I'm working in thread ${Thread.currentThread().name}")
}
jobs += launch(CommonPool) {
println("'CommonPool': I'm working in thread ${Thread.currentThread().name}")
}
jobs += launch(newSingleThreadContext("MyOwnThread")) {
println("'newSTC': I'm working in thread ${Thread.currentThread().name}")
}
jobs.forEach { it.join() }
}
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
fun main(args: Array<String>) = runBlocking<Unit> {
launch {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // just quit after delay
}
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
fun main(args: Array<String>) = runBlocking<Unit> {
val job = launch {
try {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
} finally {
println("I'm running finally")
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
}
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
main: I'm tired of waiting!
I'm running finally
main: Now I can quit.
fun main(args: Array<String>) = runBlocking<Unit> {
withTimeout(1300L) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
} I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
Exception in thread "main" kotlinx.{…}.TimeoutCancellationException …
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
https://goo.gl/2Tyx4B
Kotlin의 코루틴은 어떻게 동작하는가

More Related Content

PDF
Java開発の強力な相棒として今すぐ使えるGroovy
PPTX
[0903 구경원] recast 네비메쉬
PDF
상상을 현실로 만드는, 이미지 생성 모델을 위한 엔지니어링
PDF
リアクティブプログラミング
PDF
하드웨어 스타트업의 소프트웨어 이야기
PDF
ソフトウェア開発における『知の高速道路』
PDF
Everyday Life with clojure.spec
PDF
技術者が知るべき Gröbner 基底
Java開発の強力な相棒として今すぐ使えるGroovy
[0903 구경원] recast 네비메쉬
상상을 현실로 만드는, 이미지 생성 모델을 위한 엔지니어링
リアクティブプログラミング
하드웨어 스타트업의 소프트웨어 이야기
ソフトウェア開発における『知の高速道路』
Everyday Life with clojure.spec
技術者が知るべき Gröbner 基底

What's hot (20)

PDF
gRPC入門
PDF
CuPy解説
PDF
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
PDF
リーンなコードを書こう:実践的なオブジェクト指向設計
PDF
KorQuAD introduction
PPTX
C# 8.0 null許容参照型
PDF
Twitterのsnowflakeについて
PDF
【学会発表】U-Net++とSE-Netを統合した画像セグメンテーションのための転移学習モデル【IBIS2020】
PPTX
자기소개서, 이력서 쓰는 법
PPTX
신입 SW 개발자 취업 준비
PDF
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ
PDF
Pythonによる黒魔術入門
PDF
20分くらいでわかった気分になれるC++20コルーチン
PDF
Learning Convolutional Neural Networks for Graphs
PDF
멀티스레드 렌더링 (Multithreaded rendering)
PDF
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018
PDF
静的型つき組版処理システムSATySFi @第61回プログラミング・シンポジウム
PDF
文字列検索のいろいろ
PDF
lispmeetup#63 Common Lispでゼロから作るDeep Learning
PDF
グラフニューラルネットワーク入門
gRPC入門
CuPy解説
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
リーンなコードを書こう:実践的なオブジェクト指向設計
KorQuAD introduction
C# 8.0 null許容参照型
Twitterのsnowflakeについて
【学会発表】U-Net++とSE-Netを統合した画像セグメンテーションのための転移学習モデル【IBIS2020】
자기소개서, 이력서 쓰는 법
신입 SW 개발자 취업 준비
constexpr関数はコンパイル時処理。これはいい。実行時が霞んで見える。cpuの嬌声が聞こえてきそうだ
Pythonによる黒魔術入門
20分くらいでわかった気分になれるC++20コルーチン
Learning Convolutional Neural Networks for Graphs
멀티스레드 렌더링 (Multithreaded rendering)
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018
静的型つき組版処理システムSATySFi @第61回プログラミング・シンポジウム
文字列検索のいろいろ
lispmeetup#63 Common Lispでゼロから作るDeep Learning
グラフニューラルネットワーク入門
Ad

Similar to Kotlin의 코루틴은 어떻게 동작하는가 (20)

PPTX
Kotlin coroutines
PDF
Deep dive into Coroutines on JVM @ KotlinConf 2017
PDF
Dive into kotlins coroutines
PDF
かとうの Kotlin 講座 こってり版
PDF
Dip into Coroutines - KTUG Munich 202303
PDF
Kotlin coroutine - behind the scenes
PDF
Kotlin : Advanced Tricks - Ubiratan Soares
PDF
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022
PDF
Finagle By Twitter Engineer @ Knoldus
PPTX
C++ Lambda and concurrency
PDF
Generics and Inference
PDF
Kotlin Coroutines. Flow is coming
PDF
Kotlin - Coroutine
PDF
Tackling Asynchrony with Kotlin Coroutines
PDF
Coroutines in Kotlin. In-depth review
PDF
Coroutines in Kotlin. UA Mobile 2017.
PDF
Go ahead, make my day
PDF
Creating an Uber Clone - Part XIII.pdf
PDF
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
PDF
Introduction to Coroutines @ KotlinConf 2017
Kotlin coroutines
Deep dive into Coroutines on JVM @ KotlinConf 2017
Dive into kotlins coroutines
かとうの Kotlin 講座 こってり版
Dip into Coroutines - KTUG Munich 202303
Kotlin coroutine - behind the scenes
Kotlin : Advanced Tricks - Ubiratan Soares
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022
Finagle By Twitter Engineer @ Knoldus
C++ Lambda and concurrency
Generics and Inference
Kotlin Coroutines. Flow is coming
Kotlin - Coroutine
Tackling Asynchrony with Kotlin Coroutines
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. UA Mobile 2017.
Go ahead, make my day
Creating an Uber Clone - Part XIII.pdf
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
Introduction to Coroutines @ KotlinConf 2017
Ad

More from Chang W. Doh (20)

PDF
Exploring what're new in Web for the Natively app
PDF
Hey Kotlin, How it works?
PDF
Kotlin, 어떻게 동작하나요
PDF
introduction to Web Assembly
PDF
PWA Roadshow Seoul - Keynote
PDF
PWA Roadshow Seoul - HTTPS
PDF
CSS 다시 파서 어디에 쓰나
PDF
Natively Web App & Service Worker
PDF
초보 개발자를 위한 웹 프론트엔드 개발 101
PDF
Service Worker 201 (한국어)
PDF
Service Worker 201 (en)
PDF
Service Worker 101 (en)
PDF
Service Worker 101 (한국어)
PDF
What is next for the web
PDF
Instant and offline apps with Service Worker
PDF
Chrome enchanted 2015
PDF
프론트엔드 개발자를 위한 크롬 렌더링 성능인자 이해하기
PDF
Polymer Codelab: Before diving into polymer
PDF
알아봅시다, Polymer: Web Components & Web Animations
PDF
SOSCON 2014: 문서 기반의 오픈소스 기여하기
Exploring what're new in Web for the Natively app
Hey Kotlin, How it works?
Kotlin, 어떻게 동작하나요
introduction to Web Assembly
PWA Roadshow Seoul - Keynote
PWA Roadshow Seoul - HTTPS
CSS 다시 파서 어디에 쓰나
Natively Web App & Service Worker
초보 개발자를 위한 웹 프론트엔드 개발 101
Service Worker 201 (한국어)
Service Worker 201 (en)
Service Worker 101 (en)
Service Worker 101 (한국어)
What is next for the web
Instant and offline apps with Service Worker
Chrome enchanted 2015
프론트엔드 개발자를 위한 크롬 렌더링 성능인자 이해하기
Polymer Codelab: Before diving into polymer
알아봅시다, Polymer: Web Components & Web Animations
SOSCON 2014: 문서 기반의 오픈소스 기여하기

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Big Data Technologies - Introduction.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
KodekX | Application Modernization Development
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Weekly Chronicles - August'25 Week I
Understanding_Digital_Forensics_Presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
“AI and Expert System Decision Support & Business Intelligence Systems”
Big Data Technologies - Introduction.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MIND Revenue Release Quarter 2 2025 Press Release
KodekX | Application Modernization Development
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Empathic Computing: Creating Shared Understanding
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation_ Review paper, used for researhc scholars
Unlocking AI with Model Context Protocol (MCP)
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Kotlin의 코루틴은 어떻게 동작하는가

  • 33. fun fetchUserDetail(id: String) { val token = auth() val user = getUser(token, id) updateUserData(user) } Waaaaa~~it 😵 😵
  • 34. fun fetchUserDetail(id: String) { auth { token -> getUser(token) { updateUserData(it) } } }
  • 35. suspend fun fetchUserDetail(id: String) { val token = auth() val user = getUser(token, id) updateUserData(user) } suspend
  • 38. fun plusOne(initial: Int) : Int { val ONE = 1 var result = initial result += ONE return result }
  • 48. public interface Continuation<in T> { } public val context: CoroutineContext public fun resume(value: T) public fun resumeWithException(exception: Throwable)
  • 49. suspend fun fetchUserDetail(id: String) { val token = auth() val user = getUser(token, id) updateUserData(user) } }
  • 50. suspend fun fetchUserDetail(id: String) { // ... switch (label) { case 0: val token = auth() case 1: val user = getUser(token, id) case 2: updateUserData(user) } }
  • 51. fun fetchUserDetail(id: String) { // ... switch (label) { case 0: val token = auth() case 1: val user = getUser(token, id) case 2: updateUserData(user) } }
  • 52. fun fetchUserDetail(id: String, cont: Continuation) { switch ( label) { case 0: auth( ) case 1: getUser(token, id ) case 2: … } } val sm = object : CoroutineImpl { ... } sm. sm , sm
  • 53. fun fetchUserDetail(id: String, cont: Contiunation) { val sm = object : CoroutineImpl { ... } switch (sm.label) { case 0: auth(sm) case 1: getUser(token, id, sm) case 2: … } }
  • 54. fun fetchUserDetail(id: String, cont: Contiunation) { val sm = object : CoroutineImpl { ... } switch (sm.label) { case 0: sm.id = id sm.label = 1 auth(sm) … } }
  • 55. fun fetchUserDetail(id: String, cont: Contiunation) { val sm = object : CoroutineImpl { ... } switch (sm.label) { … case 1: val id = sm.id val token = sm.result as String sm.label = 2 getUser(token, id, sm) … }
  • 56. fun fetchUserDetail(id: String, cont: Contiunation) { val sm = object : CoroutineImpl { fun resume(...) { fetchUserDetail(null, this) } } switch (sm.label) { case 0: … } }
  • 57. fun fetchUserDetail(id: String, cont: Contiunation) { val sm = cont as? ThisSM ?: object : CoroutineImpl { fun resume(...) { fetchUserDetail(null, this) } } switch (sm.label) { case 0: … } }
  • 60. public interface Continuation<in T> { } public val context: CoroutineContext public fun resume(value: T) public fun resumeWithException(exception: Throwable)
  • 62. fun updateUserDetail(id: String) = launch(UI) { val token = auth() val user = getUser(token, id) updateUserDataOntoUI(user) }
  • 64. class DispatchedContinuation<in T> ( val dispatcher: CoroutineDispatcher, val continuation: Continuation<T> ) : Continuation<T> by continuation { override fun resume(value: T) { dispatcher.dispatch(context, DispatchTask(...)) } ... }
  • 65. fun launchOnUiThread() { launch(UI) { delay(1000L) ... } } /** * Dispatches execution onto Android main UI thread * and provides native [delay][Delay.delay] support. */ val UI = HandlerContext(Handler(Looper.getMainLooper()), "UI")
  • 66. fun main(args: Array<String>) = runBlocking<Unit> { val jobs = arrayListOf<Job>() jobs += launch(Unconfined) { println("'Unconfined': I'm working in thread ${Thread.currentThread().name}") } jobs += launch(coroutineContext) { println("'coroutineContext': I'm working in thread ${Thread.currentThread().name}") } jobs += launch(CommonPool) { println("'CommonPool': I'm working in thread ${Thread.currentThread().name}") } jobs += launch(newSingleThreadContext("MyOwnThread")) { println("'newSTC': I'm working in thread ${Thread.currentThread().name}") } jobs.forEach { it.join() } }
  • 69. fun main(args: Array<String>) = runBlocking<Unit> { launch { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } } delay(1300L) // just quit after delay } I'm sleeping 0 ... I'm sleeping 1 ... I'm sleeping 2 ...
  • 70. fun main(args: Array<String>) = runBlocking<Unit> { val job = launch { try { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } } finally { println("I'm running finally") } } delay(1300L) // delay a bit println("main: I'm tired of waiting!") job.cancelAndJoin() // cancels the job and waits for its completion println("main: Now I can quit.") } I'm sleeping 0 ... I'm sleeping 1 ... I'm sleeping 2 ... main: I'm tired of waiting! I'm running finally main: Now I can quit.
  • 71. fun main(args: Array<String>) = runBlocking<Unit> { withTimeout(1300L) { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } } } I'm sleeping 0 ... I'm sleeping 1 ... I'm sleeping 2 ... Exception in thread "main" kotlinx.{…}.TimeoutCancellationException …