SlideShare a Scribd company logo
1 of 46
Download to read offline
), (
• ) 3
• +
•
•
•
3 :
• :
• ( , : #
-
- -
*
*
*
fun requestToken(): Token { ... }
fun createTweet(token: Token, message: String): Tweet { ... }
fun processTweet(tweet: Tweet) { ... }
fun requestToken(): Token { ... }
fun createTweet(token: Token, message: String): Tweet { ... }
fun processTweet(tweet: Tweet) { ... }
fun postTweet(message: String) {
val token = requestToken()
val tweet = createTweet(token, message)
processTweet(tweet)
}
fun requestTokenAsync(cb: (Token) -> Unit) { ... }
fun createTweetAsync(token: Token, message: String, cb: (Tweet) -> Unit) { ... }
fun processTweetAsync(tweet: Tweet) { ... }
fun requestTokenAsync(cb: (Token) -> Unit) { ... }
fun createTweetAsync(token: Token, message: String, cb: (Tweet) -> Unit) { ... }
fun processTweetAsync(tweet: Tweet) { ... }
fun postTweet(message: String) {
requestTokenAsync { token ->
createPostAsync(token, message) { post ->
processPostAsync(post)
}
}
}
Callback Hell!
fun requestToken(): Observable<Token> { ... }
fun createTweet(token: Token, message: String): Observable<Tweet> { ... }
fun processTweet(tweet: Tweet) { ... }
fun postTweet(message: String) {
requestToken()
.subscribeOn(Schedulers.io())
.flatMap { token -> createTweet(token, message) }
.subscribe { tweet ->
processTweet()
}
}
fun requestToken(): Observable<Token> { ... }
fun createTweet(token: Token, message: String): Observable<Tweet> { ... }
fun processTweet(tweet: Tweet) { ... }
Not intuitive.
Learning curve is high
suspend fun requestToken(): Token { ... }
suspend fun createTweet(token: Token, message: String): Tweet { ... }
suspend fun processTweet(tweet: Tweet) { ... }
suspend fun requestToken(): Token { ... }
suspend fun createTweet(token: Token, message: String): Tweet { ... }
suspend fun processTweet(tweet: Tweet) { ... }
! ! !!
fun postTweet(message: String) = runBlocking {
launch {
val token = requestToken()
val tweet = createTweet(token, message)
processTweet(tweet)
}
}
Coroutine builder
fun main(args: Array<String>) {
val jobs = List(10000) {
thread {
Thread.sleep(1000)
print(“${Thread.currentThread().name}n”)
}
}
jobs.forEach { it.join() }
}
fun main(args: Array<String>) {
val jobs = List(10000) {
launch {
delay(1000)
print(“${Thread.currentThread().name}n”)
}
}
jobs.forEach { it.join() }
}
!!
( :
• : : - . suspend
) : .
• ( ) - :
)
• - : stdlib
kotlinx.coroutines
Kotlin’s Coroutines
( :
• : : - . suspend
) : .
• ( ) - :
)
• - :
kotlinx.coroutinesCore
API
kotlin
1.2
Kotlin’s Coroutines
suspend fun method(): Int
fun method(block: suspend () -> Int): Int
fun method(block: suspend Int.() -> Int): Int
suspend
!
fun postTweet(message: String) = runBlocking {
launch {
val token = requestToken()
val tweet = createTweet(token, message)
processTweet(tweet)
... //other non-suspending snippets
}
}
1
2
3
4
public static final Object method(Continuation<? super Integer> cont)
public static final Integer method(
Function1<? super Continuation<? super Integer>, ? extends Object> block)
public static final Integer method(
Function2<? super Integer, ? super Continuation<? super Integer>, ? extends
Object> block)
* *
Continuation Passing Style (CPS)
public interface Continuation<in T> {
public val context: CoroutineContext
public fun resume(value: T)
public fun resumeWithException(exception: Throwable)
}
public interface Continuation<in T> {
public val context: CoroutineContext
public fun resume(result: Result<T>)
}
public inline class Result<out T>(internal value: Any?) {
public val isSuccess: Boolean = value !is Failure
public val isFailure: Boolean = value is Failure
}
@SinceKotlin("1.1")
public actual val COROUTINE_SUSPENDED: Any get() = CoroutineSuspendedMarker
private object CoroutineSuspendedMarker
public static final Object postTweet(Continuation<Unit> cont) {
if(cont instanceof CoroutineImpl$1) {
...
} else {
Continuation contImpl = new CoroutineImpl(cont) {
Object data;
Throwable exception;
public final Object onResume(Object data, Throwable throwable) {
this.data = data;
this.exception = throwable;
this.label |= Integer.MIN_VALUE;
return method(this);
}
};
}
}
Anonymous class
Continuation contImpl = ...
data = contImpl.data
exception = contImpl.exception
isSuspended = IntrinsicsKt.getCOROUTINE_SUSPENDED();
switch(contImpl.getLabel()) {
case 0: {
contImpl.setLabel(1);
result = requestToken(contImpl);
if (result == isSuspended) {
return isSuspended
}
}
case 1: {
result = (String)data
return result
}
...
case n: {
}
}
1.requestToken 2.createTweet 3.processTweet
postTweet
postTweet resumeSUSPEND SUSPEND resume SUSPEND
4.non-
suspending
resume
•
•
•
•
•
•
public fun <T> (suspend () -> T).createCoroutine(completion: Continuation<T>): Continuation<Unit> =
SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED)
•
•
•
public fun <T> (suspend () -> T).startCoroutine(completion: Continuation<T>) {
createCoroutineUnchecked(completion).resume(Unit)
}
public fun <T> (suspend () -> T).createCoroutine(completion: Continuation<T>): Continuation<Unit> =
SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED)
•
•
•
public fun <T> (suspend () -> T).startCoroutine(completion: Continuation<T>) {
createCoroutineUnchecked(completion).resume(Unit)
}
public fun <T> (suspend () -> T).createCoroutine(completion: Continuation<T>): Continuation<Unit> =
SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED)
public suspend inline fun <T> suspendCoroutine(crossinline block: (Continuation<T>) -> Unit): T =
suspendCoroutineOrReturn { c: Continuation<T> ->
val safe = SafeContinuation(c)
block(safe)
safe.getResult()
}
public actual fun <T> (suspend () -> T).createCoroutineUnchecked(
completion: Continuation<T>
): Continuation<Unit> =
if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl)
buildContinuationByInvokeCall(completion) {
(this is Function1<Continuation<T>, Any?>).invoke(completion)
}
else
(this.create(completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade
public actual fun <T> (suspend () -> T).createCoroutineUnchecked(
completion: Continuation<T>
): Continuation<Unit> =
if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl)
buildContinuationByInvokeCall(completion) {
(this is Function1<Continuation<T>, Any?>).invoke(completion)
}
else
(this.create(completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade
private var _facade: Continuation<Any?>? = null
val facade: Continuation<Any?> get() {
if (_facade == null) _facade = interceptContinuationIfNeeded(_context!!, this)
return _facade!!
}
@Volatile
private var result: Any? = initialResult
internal actual class SafeContinuation <in T>
internal actual constructor(
class val delegate: Continuation<T>,
initialResult: Any?
) : Continuation<T>
private class Fail(val exception: Throwable)
internal actual fun getResult(): Any? {
var result = this.result
if (result.compareAndSet(this, UNDECIDED, COROUTINE_SUSPENDED) return COROUTINE_SUSPENDED)
result = this.result
when {
result === RESUMED -> return COROUTINE_SUSPENDED
result is Faile -> throw result.exception
else -> else result
}
}
. - - -/- .
• 0 F 8 9 9 E 69D
FF E 87H F 7 1 D 9 K F 9 0 F
9
• 97 F 6 7 9 8 FF E F 6 7 29 79 F 67
• 796 -- / FF E H 7 6 E 7 7 9D F H9
F F E : D 7
• .F D FF F D
• . . . .
• . . . . . . . . .
• . . . . . . . .
• . . . .
•
Dive into kotlins coroutines

More Related Content

What's hot

From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
 
The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212Mahmoud Samir Fayed
 
Fresh Async with Kotlin @ QConSF 2017
Fresh Async with Kotlin @ QConSF 2017Fresh Async with Kotlin @ QConSF 2017
Fresh Async with Kotlin @ QConSF 2017Roman Elizarov
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークTsuyoshi Yamamoto
 
Broken windows de práticas ágeis
Broken windows de práticas ágeisBroken windows de práticas ágeis
Broken windows de práticas ágeisCecilia Fernandes
 
FRP: What does "declarative" mean
FRP: What does "declarative" meanFRP: What does "declarative" mean
FRP: What does "declarative" meanPeter Ovchinnikov
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
 
Python Asíncrono - Async Python
Python Asíncrono - Async PythonPython Asíncrono - Async Python
Python Asíncrono - Async PythonJavier Abadía
 
PyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUIPyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUIMoniaJ
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184Mahmoud Samir Fayed
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveEleanor McHugh
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful weddingStéphane Wirtel
 
Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data StructuresPDX Web & Design
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambaryoyomay93
 

What's hot (20)

From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212
 
Fresh Async with Kotlin @ QConSF 2017
Fresh Async with Kotlin @ QConSF 2017Fresh Async with Kotlin @ QConSF 2017
Fresh Async with Kotlin @ QConSF 2017
 
Lập trình Python cơ bản
Lập trình Python cơ bảnLập trình Python cơ bản
Lập trình Python cơ bản
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
 
Broken windows de práticas ágeis
Broken windows de práticas ágeisBroken windows de práticas ágeis
Broken windows de práticas ágeis
 
FRP: What does "declarative" mean
FRP: What does "declarative" meanFRP: What does "declarative" mean
FRP: What does "declarative" mean
 
DDS-20m
DDS-20mDDS-20m
DDS-20m
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 
Python Asíncrono - Async Python
Python Asíncrono - Async PythonPython Asíncrono - Async Python
Python Asíncrono - Async Python
 
Voce Tem Orgulho Do Seu Codigo
Voce Tem Orgulho Do Seu CodigoVoce Tem Orgulho Do Seu Codigo
Voce Tem Orgulho Do Seu Codigo
 
PyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUIPyTrening 2.0 # 15 Okienka GUI
PyTrening 2.0 # 15 Okienka GUI
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
PureScript & Pux
PureScript & PuxPureScript & Pux
PureScript & Pux
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
Distributed Data Structures
Distributed Data StructuresDistributed Data Structures
Distributed Data Structures
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambar
 

Similar to Dive into kotlins coroutines

Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - CoroutineSean Tsai
 
Kotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenesKotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenesAnh Vu
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKirill Rozov
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewDmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.UA Mobile
 
Fresh Async with Kotlin
Fresh Async with KotlinFresh Async with Kotlin
Fresh Async with KotlinC4Media
 
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가Chang W. Doh
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and ProfitAdil Akhter
 
Programação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesProgramação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesDiego Gonçalves Santos
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutinestdc-globalcode
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 
Should it be routine to use coroutines?
Should it be routine to use coroutines?Should it be routine to use coroutines?
Should it be routine to use coroutines?Ion Stefan Brosteanu
 
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드NAVER Engineering
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practiceGuilherme Garnier
 

Similar to Dive into kotlins coroutines (20)

Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
 
Kotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenesKotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenes
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Fresh Async with Kotlin
Fresh Async with KotlinFresh Async with Kotlin
Fresh Async with Kotlin
 
Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가Kotlin의 코루틴은 어떻게 동작하는가
Kotlin의 코루틴은 어떻게 동작하는가
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Kotlin Coroutines - the new async
Kotlin Coroutines - the new asyncKotlin Coroutines - the new async
Kotlin Coroutines - the new async
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
 
Programação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesProgramação assíncrona utilizando Coroutines
Programação assíncrona utilizando Coroutines
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
 
Finding Clojure
Finding ClojureFinding Clojure
Finding Clojure
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Should it be routine to use coroutines?
Should it be routine to use coroutines?Should it be routine to use coroutines?
Should it be routine to use coroutines?
 
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
Concurrency in Python4k
Concurrency in Python4kConcurrency in Python4k
Concurrency in Python4k
 

Recently uploaded

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 

Recently uploaded (20)

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 

Dive into kotlins coroutines

  • 1.
  • 2.
  • 3.
  • 4.
  • 6. • ) 3 • + • • • 3 : • : • ( , : #
  • 8.
  • 10.
  • 11. fun requestToken(): Token { ... } fun createTweet(token: Token, message: String): Tweet { ... } fun processTweet(tweet: Tweet) { ... }
  • 12. fun requestToken(): Token { ... } fun createTweet(token: Token, message: String): Tweet { ... } fun processTweet(tweet: Tweet) { ... } fun postTweet(message: String) { val token = requestToken() val tweet = createTweet(token, message) processTweet(tweet) }
  • 13. fun requestTokenAsync(cb: (Token) -> Unit) { ... } fun createTweetAsync(token: Token, message: String, cb: (Tweet) -> Unit) { ... } fun processTweetAsync(tweet: Tweet) { ... }
  • 14. fun requestTokenAsync(cb: (Token) -> Unit) { ... } fun createTweetAsync(token: Token, message: String, cb: (Tweet) -> Unit) { ... } fun processTweetAsync(tweet: Tweet) { ... } fun postTweet(message: String) { requestTokenAsync { token -> createPostAsync(token, message) { post -> processPostAsync(post) } } } Callback Hell!
  • 15. fun requestToken(): Observable<Token> { ... } fun createTweet(token: Token, message: String): Observable<Tweet> { ... } fun processTweet(tweet: Tweet) { ... }
  • 16. fun postTweet(message: String) { requestToken() .subscribeOn(Schedulers.io()) .flatMap { token -> createTweet(token, message) } .subscribe { tweet -> processTweet() } } fun requestToken(): Observable<Token> { ... } fun createTweet(token: Token, message: String): Observable<Tweet> { ... } fun processTweet(tweet: Tweet) { ... } Not intuitive. Learning curve is high
  • 17. suspend fun requestToken(): Token { ... } suspend fun createTweet(token: Token, message: String): Tweet { ... } suspend fun processTweet(tweet: Tweet) { ... }
  • 18. suspend fun requestToken(): Token { ... } suspend fun createTweet(token: Token, message: String): Tweet { ... } suspend fun processTweet(tweet: Tweet) { ... } ! ! !! fun postTweet(message: String) = runBlocking { launch { val token = requestToken() val tweet = createTweet(token, message) processTweet(tweet) } } Coroutine builder
  • 19. fun main(args: Array<String>) { val jobs = List(10000) { thread { Thread.sleep(1000) print(“${Thread.currentThread().name}n”) } } jobs.forEach { it.join() } }
  • 20. fun main(args: Array<String>) { val jobs = List(10000) { launch { delay(1000) print(“${Thread.currentThread().name}n”) } } jobs.forEach { it.join() } } !!
  • 21.
  • 22. ( : • : : - . suspend ) : . • ( ) - : ) • - : stdlib kotlinx.coroutines Kotlin’s Coroutines
  • 23. ( : • : : - . suspend ) : . • ( ) - : ) • - : kotlinx.coroutinesCore API kotlin 1.2 Kotlin’s Coroutines
  • 24. suspend fun method(): Int fun method(block: suspend () -> Int): Int fun method(block: suspend Int.() -> Int): Int
  • 26. !
  • 27. fun postTweet(message: String) = runBlocking { launch { val token = requestToken() val tweet = createTweet(token, message) processTweet(tweet) ... //other non-suspending snippets } } 1 2 3 4
  • 28. public static final Object method(Continuation<? super Integer> cont) public static final Integer method( Function1<? super Continuation<? super Integer>, ? extends Object> block) public static final Integer method( Function2<? super Integer, ? super Continuation<? super Integer>, ? extends Object> block) * * Continuation Passing Style (CPS)
  • 29. public interface Continuation<in T> { public val context: CoroutineContext public fun resume(value: T) public fun resumeWithException(exception: Throwable) }
  • 30. public interface Continuation<in T> { public val context: CoroutineContext public fun resume(result: Result<T>) } public inline class Result<out T>(internal value: Any?) { public val isSuccess: Boolean = value !is Failure public val isFailure: Boolean = value is Failure }
  • 31. @SinceKotlin("1.1") public actual val COROUTINE_SUSPENDED: Any get() = CoroutineSuspendedMarker private object CoroutineSuspendedMarker
  • 32. public static final Object postTweet(Continuation<Unit> cont) { if(cont instanceof CoroutineImpl$1) { ... } else { Continuation contImpl = new CoroutineImpl(cont) { Object data; Throwable exception; public final Object onResume(Object data, Throwable throwable) { this.data = data; this.exception = throwable; this.label |= Integer.MIN_VALUE; return method(this); } }; } } Anonymous class
  • 33. Continuation contImpl = ... data = contImpl.data exception = contImpl.exception isSuspended = IntrinsicsKt.getCOROUTINE_SUSPENDED(); switch(contImpl.getLabel()) { case 0: { contImpl.setLabel(1); result = requestToken(contImpl); if (result == isSuspended) { return isSuspended } } case 1: { result = (String)data return result } ... case n: { } }
  • 34. 1.requestToken 2.createTweet 3.processTweet postTweet postTweet resumeSUSPEND SUSPEND resume SUSPEND 4.non- suspending resume
  • 36. • • • public fun <T> (suspend () -> T).createCoroutine(completion: Continuation<T>): Continuation<Unit> = SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED)
  • 37. • • • public fun <T> (suspend () -> T).startCoroutine(completion: Continuation<T>) { createCoroutineUnchecked(completion).resume(Unit) } public fun <T> (suspend () -> T).createCoroutine(completion: Continuation<T>): Continuation<Unit> = SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED)
  • 38. • • • public fun <T> (suspend () -> T).startCoroutine(completion: Continuation<T>) { createCoroutineUnchecked(completion).resume(Unit) } public fun <T> (suspend () -> T).createCoroutine(completion: Continuation<T>): Continuation<Unit> = SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED) public suspend inline fun <T> suspendCoroutine(crossinline block: (Continuation<T>) -> Unit): T = suspendCoroutineOrReturn { c: Continuation<T> -> val safe = SafeContinuation(c) block(safe) safe.getResult() }
  • 39. public actual fun <T> (suspend () -> T).createCoroutineUnchecked( completion: Continuation<T> ): Continuation<Unit> = if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl) buildContinuationByInvokeCall(completion) { (this is Function1<Continuation<T>, Any?>).invoke(completion) } else (this.create(completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade
  • 40. public actual fun <T> (suspend () -> T).createCoroutineUnchecked( completion: Continuation<T> ): Continuation<Unit> = if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl) buildContinuationByInvokeCall(completion) { (this is Function1<Continuation<T>, Any?>).invoke(completion) } else (this.create(completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade private var _facade: Continuation<Any?>? = null val facade: Continuation<Any?> get() { if (_facade == null) _facade = interceptContinuationIfNeeded(_context!!, this) return _facade!! }
  • 41. @Volatile private var result: Any? = initialResult internal actual class SafeContinuation <in T> internal actual constructor( class val delegate: Continuation<T>, initialResult: Any? ) : Continuation<T> private class Fail(val exception: Throwable) internal actual fun getResult(): Any? { var result = this.result if (result.compareAndSet(this, UNDECIDED, COROUTINE_SUSPENDED) return COROUTINE_SUSPENDED) result = this.result when { result === RESUMED -> return COROUTINE_SUSPENDED result is Faile -> throw result.exception else -> else result } }
  • 42.
  • 43. . - - -/- .
  • 44. • 0 F 8 9 9 E 69D FF E 87H F 7 1 D 9 K F 9 0 F 9 • 97 F 6 7 9 8 FF E F 6 7 29 79 F 67 • 796 -- / FF E H 7 6 E 7 7 9D F H9 F F E : D 7 • .F D FF F D
  • 45. • . . . . • . . . . . . . . . • . . . . . . . . • . . . . •