You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
explain to a satisfactory level how coroutines work.
CPS
Continuation Passing Style
Continuation 을 Function2Function 으로 전달해간다.
suspend fun getUser(): User?
-> fun getUser(continuation: Continuation<*>) : Any?
suspend fun setUser(user: User)
-> fun setUser(user: User, continuation: Continuation<*>) : Any?
suspend fun checkAvailability(flight: Flight) : Boolean
-> fun checkAvailability(flight: Flight, continuation: Continuation<*>) : Any
suspend func 변환 후
// as-issuspendfunmyFunction() {
println("Before")
delay(1000)
println("After")
}
// to-befunmyFunction(continuation:Continuation<*>) : Any {
// continuation 을 해당 function 의 continuation 으로 생성 및 반환 해주는 전처리 작업이 추가된다.// MyFunctionContinuation 이라는 naming 이 되지는 않고, 이해를 돕기 쉬운 네이밍이다.val continuation = continuation as?MyFunctionContinuation?MyFunctionContinuation(continuation)
// label 에 맞춰서 suspend 전과 후 상태를 보장하고 처리를 분리한다.if (continuation.label ==0) {
println("Before")
continuation.label =1if (delay(1000, continuation) ==COROUTINE_SUSPENDED)
returnCOROUTINE_SUSPENDED
}
if (continuation.label ==1) {
println("After")
returnUnit
}
error("Imposible")
}
classMyFunctionContinuation( valcompletion:Continuation<Unit>) : Continuation<Unit> {
overrideval context :CoroutineContext
get() = completion.context
// status 를 가진다.val label =0var result :Result<Any> ?=nulloverridefunresumeWith(result:Result<String>) {
this.result = result
val res =try {
val r = myFunction(this)
if ( r ==COROUTINE_SUSPENDED) returnResult.success(r asUnit)
} catch (t :Throwable) {
Result.failure(t)
}
completion.resumeWith(res)
}
}
State machine
suspend 를 위해 각 function 들은 상태를 가지게 된다.
The text was updated successfully, but these errors were encountered:
coroutine 이 실제로 어떻게 동작되어지는가?
CPS
Continuation Passing Style
suspend fun getUser(): User?
-> fun getUser(continuation: Continuation<*>) : Any?
suspend fun setUser(user: User)
-> fun setUser(user: User, continuation: Continuation<*>) : Any?
suspend fun checkAvailability(flight: Flight) : Boolean
-> fun checkAvailability(flight: Flight, continuation: Continuation<*>) : Any
suspend func 변환 후
State machine
suspend 를 위해 각 function 들은 상태를 가지게 된다.
The text was updated successfully, but these errors were encountered: