看不懂很正常,老师的操作对综合能力要求太高了,多看几遍,一步一步拆解就很简单了。参照老师的代码写了一个只专注协程的例子分享一下~

来源:11-7 案例:Generator 与标准库的序列生成器

qiHuang112

2022-11-05

代码里涉及到的知识点太多了,协程理解起来本来就困难,再糅杂一些高阶函数,操作符重载,密封类等等骚操作,确实懵逼。

简化之后其实很简单了。

import base.Log
import kotlin.coroutines.*

interface Operators {
    suspend fun eat()
    suspend fun sleep()
    suspend fun shopping()
}

class MyOperators(suspendOptions: suspend Operators.() -> Unit) : Operators, Continuation<Unit> {
    override val context = EmptyCoroutineContext
    private var value: String? = null
    private var end = false

    private var continuation: Continuation<Unit>

    init {
        continuation = suspendOptions.createCoroutine(this, this)
    }

    override suspend fun eat() = suspendCoroutine {
        continuation = it
        this.value = "eat"
    }

    override suspend fun sleep() = suspendCoroutine {
        continuation = it
        this.value = "sleep"
    }

    override suspend fun shopping() = suspendCoroutine {
        continuation = it
        this.value = "shopping"
    }

    override fun resumeWith(result: Result<Unit>) {
        end = true
        result.getOrThrow()
    }

    fun next(): String {
        return if (end) {
            "事情都做完了 没事儿干了!!!"
        } else if (value == null) {
            continuation.resume(Unit)
            next()
        } else {
            val value = this.value!!
            this.value = null
            value
        }
    }
}

fun main() {
    val suspendOptions: suspend Operators.() -> Unit = {
        eat()
        sleep()
        shopping()
        sleep()
        eat()
    }
    MyOperators(suspendOptions).apply {
        next().let(Log::d)
        next().let(Log::d)
        next().let(Log::d)
        next().let(Log::d)
        next().let(Log::d)
        next().let(Log::d)
    }

}
写回答

4回答

cutler

2023-01-27

我花了300多元,不就来享受学习的吗?

现在的情况是,钱花了,结果课程内容东一榔头西一棒,还得我再去搜索其它教程,然后对比、测试、总结,这和自学有什么区别?

那我花的钱,价值提现在哪?

1
0

JefferyzZ

2023-04-25

懵逼了一圈,还好从你这个案例看懂了

0
0

全干菜鸡

2023-03-28

非常感谢你这个案例,不然我是真的看不懂

0
0

bennyhuo

2022-11-05

不错啊小伙~

0
0

学会Kotlin 突破开发语言瓶颈

如果有一门语言可以取代Java,那么它一定是Kotlin。

1760 学习 · 481 问题

查看课程