Skip to content

Instantly share code, notes, and snippets.

View chaxiu's full-sized avatar
🎯
Focusing

BoyCoder chaxiu

🎯
Focusing
View GitHub Profile

Diagram Coroutines: suspend

1. Preface

Coroutines is the most amazing feature in Kotlin.

In this post, I'll briefly introduce Kotlin coroutines, and then explain Coroutines in the form of Diagram + Animation. After reading this post, you may find out that Coroutines is not that difficult.

Coroutines-dispatch

// Have fun!
@Nullable
public static final Object testCoroutine(@NotNull Continuation $completion) {
Object $continuation;
label37: {
if ($completion instanceof <TestSuspendKt$testCoroutine$1>) {
$continuation = (<TestSuspendKt$testCoroutine$1>)$completion;
if ((((<TestSuspendKt$testCoroutine$1>)$continuation).label & Integer.MIN_VALUE) != 0) {
((<TestSuspendKt$testCoroutine$1>)$continuation).label -= Integer.MIN_VALUE;
break label37;
@chaxiu
chaxiu / block21.kt
Last active October 18, 2020 13:54
// pseudocode
// marked by label
// ↓ ↓
label: whenStart
when (continuation.label) {
0 -> {
...
}
1 -> {
if (suspendReturn == sFlag) {
} else {
// What is the specific code?
// ↓
//go to next state
}
when (continuation.label) {
0 -> {
...
}
1 -> {
...
// function name changed
// ↓
suspendReturn = noSuspendFriendList(user, continuation)
// "fake" suspending function
// Although it has suspend modifier,
// it will not really suspend when executed,
// because there is no other suspending in its body
// ↓
suspend fun noSuspendFriendList(user: String): String{
return "Tom, Jack"
}
suspend fun testNoSuspend() {
when (continuation.label) {
0 -> {
// check exceptions
throwOnFailure(result)
log("start")
// Assign 1 to label, ready for the next state
continuation.label = 1
// Call getUserInfo()
// Three variables, corresponding to the three variables of the original function
lateinit var user: String
lateinit var friendList: String
lateinit var feedList: String
// The running result of the coroutine
var result = continuation.result
// The return of the suspending function
var suspendReturn: Any? = null
// ↓
fun testCoroutine(completion: Continuation<Any?>): Any? {
...
val continuation = if (completion is TestContinuation) {
completion
} else {
// As parameter
// ↓
TestContinuation(completion)
}
fun testCoroutine(completion: Continuation<Any?>): Any? {
class TestContinuation(completion: Continuation<Any?>?) : ContinuationImpl(completion) {
// Represents the current state of the coroutines state machine
var label: Int = 0
// Coroutines results
var result: Any? = null
// Used to save the calculation results of the previous coroutine
var mUser: Any? = null