Kotlin随笔

  1. Coroutine优势:性能快,语法简单,业务清晰
    Thread性能差,Callback业务嵌套过多时容易产生回调地狱,RxJava不熟悉的人不会合理运用链式函数编程。

  2. 自定义协程拦截器:
    版权声明:本文为CSDN博主「不会写代码的丝丽」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qfanmingyiq/article/details/105181027
    完整代码:

class MyCoroutineDispatch : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {

    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        log("interceptContinuation")
        return MyInterceptorContinuation<T>(continuation.context, continuation)
    }

    override fun releaseInterceptedContinuation(continuation: Continuation<*>) {
        super.releaseInterceptedContinuation(continuation)

        log("releaseInterceptedContinuation " + continuation::class.java.simpleName)
    }


    class MyInterceptorContinuation<T>(
        override val context: CoroutineContext,
        val continuation: Continuation<T>
    ) : Continuation<T> {


        override fun resumeWith(result: Result<T>) {
            //获取Android主线程的Looper,进而切换主线程
            Handler(Looper.getMainLooper()).post {
                log("MyInterceptorContinuation resume")
                continuation.resumeWith(result)
            }

        }

    }
}

class MyContinuation() : Continuation<String> {
    //这里不在使用空上下文
    override val context: CoroutineContext = MyCoroutineDispatch()
    override fun resumeWith(result: Result<String>) {
        log("MyContinuation resumeWith 结果 = ${result.getOrNull()}")
    }

}

suspend fun demo() = suspendCoroutine<String> { c ->

    thread(name = "demo1创建的线程") {
        log("demo 调用resume回调")
        c.resume("hello")
    }

}

suspend fun demo2() = suspendCoroutine<String> { c ->
    thread(name = "demo2创建的线程") {
        log("demo2 调用resume回调")
        c.resume("world")
    }
}

fun testInterceptor() {


    // 假设下面的lambda需要在UI线程运行
    val suspendLambda = suspend {
        log("demo 运行前")
        val resultOne = demo()
        log("demo 运行后")
        val resultTwo = demo2()
        log("demo2 运行后")
        //拼接结果
        resultOne + resultTwo
    }

    val myContinuation = MyContinuation()

    thread(name = "一个新的线程") {
        suspendLambda.startCoroutine(myContinuation)

    }
}

fun log(msg: String) {

    Log.e("TAG","[${Thread.currentThread().name}] ${msg}")
}

上文代码输出结果:

[一个新的线程] interceptContinuation
[main] MyInterceptorContinuation resume
[main] demo 运行前
[demo1创建的线程] demo 调用resume回调
[main] MyInterceptorContinuation resume
[main] demo 运行后
[demo2创建的线程] demo2 调用resume回调
[main] MyInterceptorContinuation resume
[main] demo2 运行后
[main] releaseInterceptedContinuation MyInterceptorContinuation
[main] MyContinuation resumeWith 结果 = helloworld

自定义协程拦截器:

class MyCoroutineDispatch : 
AbstractCoroutineContextElement(ContinuationInterceptor),
ContinuationInterceptor {
}

我们继承AbstractCoroutineContextElement类,并实现了ContinuationInterceptor接口,我们分别看看各自的用处。
AbstractCoroutineContextElement 的声明:

public abstract class AbstractCoroutineContextElement(public override val key: Key<*>) : Element

可以看到了实现了Element接口其实就是一个协程上下文 :

public interface Element : CoroutineContext {
        public val key: Key<*>

        public override operator fun <E : Element> get(key: Key<E>): E? =
            @Suppress("UNCHECKED_CAST")
            if (this.key == key) this as E else null

        public override fun <R> fold(initial: R, operation: (R, Element) -> R): R =
            operation(initial, this)

        public override fun minusKey(key: Key<*>): CoroutineContext =
            if (this.key == key) EmptyCoroutineContext else this
}

Element可以放入某个协程上下文中的链表存储的对象。而Element本身也是一个上下文对象。在上下文中可以用get函数或者[]操作符获取对应的存储对象。

所以这个MyCoroutineDispatch可以当做上下文使用,并且也可以放入其他上下文存储,自身的key是ContinuationInterceptor。所以他可以放入MyContinuation中做上下文对象。

再看看ContinuationInterceptor:

public interface ContinuationInterceptor : CoroutineContext.Element {
  
    companion object Key : CoroutineContext.Key<ContinuationInterceptor>
    
    public fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T>

   
    public fun releaseInterceptedContinuation(continuation: Continuation<*>) {
        /* do nothing by default */
    }
}

ContinuationInterceptor是一个拦截规范,interceptContinuation传入一个原始continuation对象,然后返回一个代理的Continuation,然后在代理Continuation中进行现场切换。如果不返回代理continuation,直接返回原始continuation 即可。当状态机结束的时候releaseInterceptedContinuation会被调用,参数是interceptContinuation返回的对象。

获取拦截器流程:
分析以下代码:

fun testInterceptor() {


    // 假设下面的lambda需要在UI线程运行
    val suspendLambda = suspend {
        log("demo 运行前")
        val resultOne = demo()
        log("demo 运行后")
        val resultTwo = demo2()
        log("demo2 运行后")
        //拼接结果
        resultOne + resultTwo
    }

    val myContinuation = MyContinuation()

    thread(name = "一个新的线程") {
        suspendLambda.startCoroutine(myContinuation)

    }
}

当遇到 suspend {}调用 startCoroutine的代码,编译器会把suspend{}编译成SuspendLambda,作为协程体。
SuspendLambda继承了ContinuationImpl,重点看看ContinuationImpl代码,注意获取context的方法:


@SinceKotlin("1.3")
// Suspension lambdas inherit from this class
internal abstract class SuspendLambda(
    public override val arity: Int,
    completion: Continuation<Any?>?
) : ContinuationImpl(completion), FunctionBase<Any?>, SuspendFunction {
    constructor(arity: Int) : this(arity, null)

    public override fun toString(): String =
        if (completion == null)
            Reflection.renderLambdaToString(this) // this is lambda
        else
            super.toString() // this is continuation
}


@SinceKotlin("1.3")
// State machines for named suspend functions extend from this class
internal abstract class ContinuationImpl(
    completion: Continuation<Any?>?,
    private val _context: CoroutineContext?
) : BaseContinuationImpl(completion) {
    //使用传入completion的上下文作为ContinuationImpl的上下文。
    //MyContinuation是completion,而MyContinuation的上下文MyCoroutineDispatch
    //MyCoroutineDispatch就是我们创建的拦截器
    constructor(completion: Continuation<Any?>?) : this(completion, completion?.context)

    public override val context: CoroutineContext
        get() = _context!!

    @Transient
    private var intercepted: Continuation<Any?>? = null

    public fun intercepted(): Continuation<Any?> =
        intercepted
            ?: (context[ContinuationInterceptor]?.interceptContinuation(this) ?: this)
                .also { intercepted = it }

    protected override fun releaseIntercepted() {
        val intercepted = intercepted
        if (intercepted != null && intercepted !== this) {
            context[ContinuationInterceptor]!!.releaseInterceptedContinuation(intercepted)
        }
        this.intercepted = CompletedContinuation // just in case
    }
}

我们再来看看个函数intercepted

//ContinuationImpl.kt
 @Transient
    private var intercepted: Continuation<Any?>? = null

    public fun intercepted(): Continuation<Any?> =
    //如果拦截器为空那么会做如下三步
    //1.上下文中获取可以为ContinuationInterceptor的拦截器
    //2.调用拦截器interceptContinuation函数获取一个代理Continuation对象。所以拦截器的interceptContinuation只会调用一次
    //3.保存拦截器返回的代理Continuation对象后面方便再次获取就不需要再次调用interceptContinuation
        intercepted
            ?: (context[ContinuationInterceptor]?.interceptContinuation(this) ?: this)
                .also {
                 //保存获取的拦截器
                 intercepted = it 
                 }

我们最后看看什么时候第一次调用intercepted的代码。

public fun <T> (suspend () -> T).startCoroutine(
    completion: Continuation<T>
) {
    createCoroutineUnintercepted(completion).intercepted().resume(Unit)
}

启动协程的时候回获取一次拦截器,然后用拦截器返回代理Continuation 去执行resume方法
再来看看我们的写的拦截器:

class MyCoroutineDispatch : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
        //intercepted()第一次调用的会调用到这里
    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        log("interceptContinuation")
        //返回一个代理Continuation对象
        return MyInterceptorContinuation<T>(continuation.context, continuation)
    }

    override fun releaseInterceptedContinuation(continuation: Continuation<*>) {
        super.releaseInterceptedContinuation(continuation)

        log("releaseInterceptedContinuation " + continuation::class.java.simpleName)
    }


    class MyInterceptorContinuation<T>(
        override val context: CoroutineContext,
        val continuation: Continuation<T>
    ) : Continuation<T> {


        override fun resumeWith(result: Result<T>) {
            //获取Android主线程的Looper,进而切换主线程
            Handler(Looper.getMainLooper()).post {
                log("MyInterceptorContinuation resume")
                //回调原始的Continuation对象
                continuation.resumeWith(result)
            }

        }

    }
}

当调用启动协程的时候会调用拦截器的代理Continuation对象的resumeWith,然后在Ui线程回调原始Continuation对象。
我们再看看我的挂起函数demo又是怎么切换回ui线程

suspend fun demo() = suspendCoroutine<String> { c ->

    thread(name = "demo1创建的线程") {
        log("demo 调用resume回调")
        c.resume("hello")
    }
}

在正常不启用拦截器的情况会回调suspendLambda在demo1创建的线程线程回调。但是我们发现启用拦截器后被在ui线程回调。而真正做切换的逻辑在suspendCoroutine这个lambda表达式上。

public suspend inline fun <T> suspendCoroutine(crossinline block: (Continuation<T>) -> Unit): T =
    suspendCoroutineUninterceptedOrReturn { c: Continuation<T> ->
        val safe = SafeContinuation(c.intercepted())//返回拦截器的代理的Continuation对象
        block(safe)
        safe.getOrThrow()
    }

这里我们便知道答案。demo()函数拿到的Continuation会经过一层拦截器代理对象,一切便自然解释的通了。
总结:拦截器返回一个代理Continuation对象给挂起函数,当挂起函数恢复的时候,恢复代理Continuation的resume函数,最后代理Continuation对象切换指定的线程在回调原始的Continuation对象。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355

推荐阅读更多精彩内容