Kotlin中的协程 - 生命周期

前言

Kotlin是一种在Java虚拟机上运行的静态类型编程语言,被称之为Android世界的Swift,在GoogleI/O2017中,Google宣布Kotlin成为Android官方开发语言

Job

当我们创建一个协程时,会返回一个Job对象,它代表了了当前正在运行的协程,可以用它去获取协程的工作状态,可以通过它随时取消协程,

val job = GlobalScope.launch {
    Log.e("Mike","start")
    delay(2000)
    Log.e("Mike","complete")
}
Thread.sleep(1000)
job.cancel()
Log.e("Mike","cancel")
打印结果
start
cancel

Job的生命周期

Job中提供了三个变量用来获取当先协程的执行情况
isActive
isCompleted
isCancelled

img.PNG

通过上述的三个变量可以很容易的判断协程当前是位于什么状态


img.PNG

New: 当我们创建了协程,但是协程并没有启动时候,在之前我们介绍过协程的不同启动模式,当我们使用Lazy模式去创建协程,协程并不会启动,而是会在New状态

val job = GlobalScope.launch(start = CoroutineStart.LAZY) {}
Log.e("Mike", "job states--isActive=${job.isActive}  isCompleted=${job.isCompleted} isCancelled=${job.isCancelled} ")
打印结果
job states--isActive=false  isCompleted=false isCancelled=false

Active: 当协程启动之后,就会处于Active状态,为了防止它进入下一状态所以增加了2秒的延时

val job = GlobalScope.launch() {
    delay(2000)
}
Log.e("Mike", "job states--isActive=${job.isActive}  isCompleted=${job.isCompleted} isCancelled=${job.isCancelled} ")
打印结果
job states--isActive=true  isCompleted=false isCancelled=false 

Completing: 当协程已经执行完毕,但还需要等待它的子协程执行,此时它的状态是完成中状态,它和Active所反映出的结果相同都是还没有执行完,差别在于此时主协程已经执行完毕,在等待子协程的执行

val job = GlobalScope.launch() {
    launch {
        delay(2000)
    }
}
Log.e("Mike", "job states--isActive=${job.isActive}  isCompleted=${job.isCompleted} isCancelled=${job.isCancelled} ")
打印结果
job states--isActive=true  isCompleted=false isCancelled=false 

Completed: 当协程已经完全执行完毕,包括内部的子协程

val job = GlobalScope.launch() {
    launch {
        delay(2000)
    }
}
Thread.sleep(3000)
Log.e("Mike", "job states--isActive=${job.isActive}  isCompleted=${job.isCompleted} isCancelled=${job.isCancelled} ")
打印结果
job states--isActive=false  isCompleted=true isCancelled=false 

Cancelling Cancelled: 当协程被取消或者有异常产生时,会进入此状态,如果父协程此时cancel掉,则会停留在Cancelling状态等待子协程·cancel,当内部子协程结束完毕之后才会进入Cancelled状态,当结束之后会回调invokeOnCompletion函数

val job = GlobalScope.launch {
    launch {
        delay(2000)
    }
}
job.invokeOnCompletion {
    Log.e("Mike", "job states completed--isActive=${job.isActive}  isCompleted=${job.isCompleted} isCancelled=${job.isCancelled} ")
}
job.cancel()
Log.e("Mike", "job states--isActive=${job.isActive}  isCompleted=${job.isCompleted} isCancelled=${job.isCancelled} ")
打印结果
job states--isActive=false  isCompleted=false isCancelled=true
//稍后
job states--isActive=false  isCompleted=true isCancelled=true  

取消一个协程

使用Scopecancel使用此Scope所创建的协程

val scope = object : CoroutineScope {
    override val coroutineContext: CoroutineContext = Dispatchers.IO + Job()
}


val job = scope.launch {
    Log.e("Mike", "main1 start")
    delay(3000)
    Log.e("Mike", "main2 end")
}

val job1 = scope.launch {
    Log.e("Mike", "main2 start")
    delay(3000)
    Log.e("Mike", "main2 end")
}

Thread.sleep(1000)
scope.cancel()
打印结果
main1 start
main2 start

Scope中的cancel扩展函数其实也是调用了Job中的cancel函数,所以如果你的Scope没有Job,比如GlobalScopeMainScope,如果调用cancel则会抛出异常提示Scope cannot be cancelled because it does not have a job

public fun CoroutineScope.cancel(cause: CancellationException? = null) {
    val job = coroutineContext[Job] ?: error("Scope cannot be cancelled because it does not have a job: $this")
    job.cancel(cause)
}

使用Jobcancel掉对应的协程

使用Job可以cancel掉它所对应的协程,以及子协程,也可以直接取消子协程,被取消的子协程不会影响其他同级的协程

  • 当父协程取消时,子协程也会跟随者取消
val job = GlobalScope.launch() {
    val childJob = launch {
        delay(2000)
    }
    childJob.invokeOnCompletion {
        Log.e("Mike", "child job canceled")

    }
    delay(3000)
}
job.invokeOnCompletion {
    Log.e("Mike", "parent job canceled")
}
Thread.sleep(1000)
job.cancel()
打印结果
child job canceled
parent job canceled
  • 当子协程出现没有捕获的异常时,异常会传递给其他子协程造成取消,也会造成父协程的取消
val errorHandle = CoroutineExceptionHandler { context, error ->
    Log.e("Mike", "coroutine error $error")
}
val job = GlobalScope.launch(errorHandle) {
    val childJob = launch {
        delay(1000)
        throw Exception("exception")
    }
    childJob.invokeOnCompletion {
        Log.e("Mike", "child job canceled")

    }
    val childJob1 = launch {
        delay(5000)
    }
    childJob1.invokeOnCompletion {
        Log.e("Mike", "child job1 canceled")

    }
    delay(3000)
}
job.invokeOnCompletion {
    Log.e("Mike", "parent job canceled")
}
打印结果
child job1 canceled
child job canceled
coroutine error java.lang.Exception: exception
parent job canceled

Job中的常用函数/属性

cancel
用于Job的取消,取消协程
start
用于启动一个协程,让其到达Active状态
invokeOnCompletion
添加一个监听,当工作完成或者异常时会调用
join
阻塞并等候当前协程完成
children
子Job链

Job的结构

前面我们提到了取消父Job也会引起子Job的取消,这是因为Job是一个链表结构,每一个Job会持有父Job以及子Job的对象,这样的结构层级关系组成了Job的结构,探讨下它是如何实现的

首先,Job是一个Element,所以它是CoroutineContext的组成部分

public interface Job : CoroutineContext.Element

默认启动模式下,当我们创建一个协程时,他会和newContext生成一个Job,它是StandaloneCoroutine类型,newContext是结合传入的Context对象以及当前作用域Context对象结合生成的当前协程的Context对象

public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job {
    val newContext = newCoroutineContext(context)
    val coroutine = if (start.isLazy)
        LazyStandaloneCoroutine(newContext, block) else
        StandaloneCoroutine(newContext, active = true)
    coroutine.start(start, coroutine, block)
    return coroutine
}

StandaloneCoroutine继承自AbstractCoroutine,将newContext传入其构造函数

private open class StandaloneCoroutine(
    parentContext: CoroutineContext,
    active: Boolean
) : AbstractCoroutine<Unit>(parentContext, active) {
    override fun handleJobException(exception: Throwable): Boolean {
        handleCoroutineException(context, exception)
        return true
    }
}

然后调用了coroutine.start(start, coroutine, block),也就是调用了AbstractCoroutinestart函数

    /**
     * Starts this coroutine with the given code [block] and [start] strategy.
     * This function shall be invoked at most once on this coroutine.
     *
     * First, this function initializes parent job from the `parentContext` of this coroutine that was passed to it
     * during construction. Second, it starts the coroutine based on [start] parameter:
     */
    public fun start(start: CoroutineStart, block: suspend () -> T) {
        initParentJob()
        start(block, this)
    }

initParentJob中会将当前Job对象添加到父Job中通过attachChild,如果父Job存在,并且在这之前如果父协程没有启动则会将其启动

    internal fun initParentJob() {
        initParentJobInternal(parentContext[Job])
    }
    internal fun initParentJobInternal(parent: Job?) {
        check(parentHandle == null)
        if (parent == null) {
            parentHandle = NonDisposableHandle
            return
        }
        parent.start() // make sure the parent is started
        @Suppress("DEPRECATION")
        val handle = parent.attachChild(this)
        parentHandle = handle
        // now check our state _after_ registering (see tryFinalizeSimpleState order of actions)
        if (isCompleted) {
            handle.dispose()
            parentHandle = NonDisposableHandle // release it just in case, to aid GC
        }
    }

我们再去看下attachChild做了什么,AbstractCoroutine继承了JobSupportattachChild实现在里面

    public final override fun attachChild(child: ChildJob): ChildHandle {
        return invokeOnCompletion(onCancelling = true, handler = ChildHandleNode(this, child).asHandler) as ChildHandle
    }

this(parent Job),child Job封装成了ChildHandleNode传入了invokeOnCompletion,此时ChildHandler的结构为{childJob:子Job对象,job:父Job对象}

    public final override fun invokeOnCompletion(
        onCancelling: Boolean,
        invokeImmediately: Boolean,
        handler: CompletionHandler
    ): DisposableHandle {
        var nodeCache: JobNode<*>? = null
        loopOnState { state ->
            when (state) {
                is Empty -> { // EMPTY_X state -- no completion handlers
                    if (state.isActive) {
                        // try move to SINGLE state
                        val node = nodeCache ?: makeNode(handler, onCancelling).also { nodeCache = it }
                        if (_state.compareAndSet(state, node)) return node
                    } else
                        promoteEmptyToNodeList(state) // that way we can add listener for non-active coroutine
                }
                is Incomplete -> {
                    val list = state.list
                    if (list == null) { // SINGLE/SINGLE+
                        promoteSingleToNodeList(state as JobNode<*>)
                    } else {
                        var rootCause: Throwable? = null
                        var handle: DisposableHandle = NonDisposableHandle
                        if (onCancelling && state is Finishing) {
                            synchronized(state) {
                                // check if we are installing cancellation handler on job that is being cancelled
                                rootCause = state.rootCause // != null if cancelling job
                                // We add node to the list in two cases --- either the job is not being cancelled
                                // or we are adding a child to a coroutine that is not completing yet
                                if (rootCause == null || handler.isHandlerOf<ChildHandleNode>() && !state.isCompleting) {
                                    // Note: add node the list while holding lock on state (make sure it cannot change)
                                    val node = nodeCache ?: makeNode(handler, onCancelling).also { nodeCache = it }
                                    if (!addLastAtomic(state, list, node)) return@loopOnState // retry
                                    // just return node if we don't have to invoke handler (not cancelling yet)
                                    if (rootCause == null) return node
                                    // otherwise handler is invoked immediately out of the synchronized section & handle returned
                                    handle = node
                                }
                            }
                        }
                        if (rootCause != null) {
                            // Note: attachChild uses invokeImmediately, so it gets invoked when adding to cancelled job
                            if (invokeImmediately) handler.invokeIt(rootCause)
                            return handle
                        } else {
                            val node = nodeCache ?: makeNode(handler, onCancelling).also { nodeCache = it }
                            if (addLastAtomic(state, list, node)) return node
                        }
                    }
                }
                else -> { // is complete
                    // :KLUDGE: We have to invoke a handler in platform-specific way via `invokeIt` extension,
                    // because we play type tricks on Kotlin/JS and handler is not necessarily a function there
                    if (invokeImmediately) handler.invokeIt((state as? CompletedExceptionally)?.cause)
                    return NonDisposableHandle
                }
            }
        }
    }

invokeOnCompletion看起来很复杂
loopOnState是一个死循环,循环读取Internal states到代码块中
当我们添加Child的时候会进入Empty中的代码,并且此时nodeCachenull

is Empty -> { // EMPTY_X state -- no completion handlers
    if (state.isActive) {
        // try move to SINGLE state
        val node = nodeCache ?: makeNode(handler, onCancelling).also { nodeCache = it }
        if (_state.compareAndSet(state, node)) return node
    } else
        promoteEmptyToNodeList(state) // that way we can add listener for non-active coroutine
}

然后会执行makeNode,此时的执行上下文为
this : 表示parent Job
handler: 是一个ChildHandleNode 封装了ChildJob

val node = nodeCache ?: makeNode(handler, onCancelling).also { nodeCache = it }

然后进入到了makeNodeif,因为onCancelling == true

    private fun makeNode(handler: CompletionHandler, onCancelling: Boolean): JobNode<*> {
        return if (onCancelling)
            (handler as? JobCancellingNode<*>)?.also { require(it.job === this) }
                ?: InvokeOnCancelling(this, handler)
        else
            (handler as? JobNode<*>)?.also { require(it.job === this && it !is JobCancellingNode) }
                ?: InvokeOnCompletion(this, handler)
    }

handler as? JobCancellingNode<*>条件满足,因为ChildHandlerNode间接继承自JobCancellingNode

if (_state.compareAndSet(state, node)) return node

然后会返回ChildHandlerNode对象 return,并将parentstate设置为node

回到initParentJobInternal中,由当前子JobparentHandle字段持有

val handle = parent.attachChild(this)
parentHandle = handle

当取消时会调用notifyCancelling,进入cancelling状态先取消自己的child,然后再取消parent

    private fun notifyCancelling(list: NodeList, cause: Throwable) {
        // first cancel our own children
        onCancelling(cause)
        notifyHandlers<JobCancellingNode<*>>(list, cause)
        // then cancel parent
        cancelParent(cause) // tentative cancellation -- does not matter if there is no parent
    }

cancelParent中调用了之前存入parentHandle,将父Job取消掉

    private fun cancelParent(cause: Throwable): Boolean {
        // CancellationException is considered "normal" and parent is not cancelled when child produces it.
        // This allow parent to cancel its children (normally) without being cancelled itself, unless
        // child crashes and produce some other exception during its completion.
        if (cause is CancellationException) return true
        if (!cancelsParent) return false
        return parentHandle?.childCancelled(cause) == true
    }

将父Job对象放入到了子ChildHandlerNode对象的job字段中去,并且父Job也持有了子Job的对象,这个是一种链表的实现,这个结构对我们来讲很重要,也解释了Job之间的关联关系,父子Job之间的链表结构,正是实现结构化并发的条件

欢迎关注Mike的简书

Android知识整理

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

推荐阅读更多精彩内容