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(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() && !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>(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知识整理

你可能感兴趣的:(Kotlin中的协程 - 生命周期)