day16 coroutine job 的那些状态,job state

前言

今天东西不多,算是给前面做一个补充资讯,明天开始会讲Flow了,又是会是超长的文章

正文

想不到吧? job也有生命周期,我没有乱套名词喔,文档自己写life-cycle的,相信大家已经对job和coroutine的父子层级结构十分清楚了吧!
不清楚的看继承这篇取消这篇

之前我们讲过job在呼叫cancel後,并不会直接取消,而是先进入canceling的状态,今天就是要讲讲job的那些状态

状态和生命周期

job的state有多重要,你先把她想像成fragment,你要在里面执行的程序都须确保fragment还活着,你说,重不重要

那job的state有哪些,分别是创建时(New)、运行中(Active)、准备完成(Completing)、完成(Completed)、取消中(Cancelling)和已取消(Cancelled六种)


source: https://medium.com/androiddevelopers/coroutines-first-things-first-e6187bf3bb21

这两张图一样,自己挑容易理解的那张看即可,job的state比起activity或fragment简单许多,只有6个状态,扣掉开始、结束、取消,剩下三种,基本上你已经学会了,然而对job的state我们并不能够直接访问状态,我们必须透过isActive, isCancelled 和isCompleted的方法,回传的boolean去检查

在边再次提醒,除了job.cancel(),当coroutine throw Exception时,也会进入canceling 状态

cancel的描述很简单,cancel()呼叫後会到canceled,但明明cancelled没有箭头到completed,这两个isCancel和isComplete却可能同时回传true,这是因为一个以取消的job也可以被视为完成; 另一方面,一个正常完成的job,她会知道自己不是被呼叫cancel()或是fail而取消的,所以正常完成的job,isCancel会是false

try {
    thirdJob.complete()
} catch (e:Exception){
    Timber.e(e)
}finally {
    Timber.d(thirdJob.isActive.toString())
    Timber.d(thirdJob.isCancelled.toString())
    Timber.d(thirdJob.isCompleted.toString())
    thirdJob.cancel()
}
delay(1000)
Timber.d(thirdJob.isActive.toString())
Timber.d(thirdJob.isCancelled.toString())
Timber.d(thirdJob.isCompleted.toString())

刺激的来了,每次印出来的结果不一定相同

D/CoroutineFragment$test: true //isActive
D/CoroutineFragment$test: false //isCancelled
D/CoroutineFragment$test: false //isCompleted
D/CoroutineFragment$test: finally-----------------------
D/CoroutineFragment$test: false //isActive
D/CoroutineFragment$test: true //isCancelled
D/CoroutineFragment$test: true //isCompleted
D/CoroutineFragment$test: outside-----------------------

cancel和complete位子互换

D/CoroutineFragment$test: false //isActive
D/CoroutineFragment$test: true //isCancelled
D/CoroutineFragment$test: false //isCompleted
D/CoroutineFragment$test: finally-----------------------
D/CoroutineFragment$test: false //isActive
D/CoroutineFragment$test: true //isCancelled
D/CoroutineFragment$test: true //isCompleted
D/CoroutineFragment$test: outside-----------------------

If we just call cancel, it doesn’t mean that the coroutine work will just stop. If you’re performing some relatively heavy computation, like reading from multiple files, there’s nothing that automatically stops your code from running.
而会造成这样的原因是当我们呼叫了cancel 或Complete时,他并不是立刻切换状态,而是会等到工作结束,这部分我在之前的cancel有讲过了,但我们依然能得到的结论,isCancelled和isCompleted的状态可以同时存在

表格,可以看到个状态对应的回传值

连结

coroutine first thing first
官方blog


<<:  Day15【Web】网路攻击:中间人攻击(MITM)

>>:  D17 - 「脉冲×宽度×调变」:PWM 功能

Day 30 - 每日产生观察名单

本篇重点 每日下载及更新Kbar资料 每日产生观察名单 结论 每日下载及更新Kbar资料 每天下载及...

Day26 - 区块链社会学读後感(上) 误解、信任

Likecoin 创办人高重建先生,最近写了一本《区块链社会学》。作者秉持「人文为主、科技为辅」,从...

Day 30 後记-TUTK跟一些P2P介绍

Tutkt P2P使用方法介绍: 连接原理为: (1) -> Device向P2P Serve...

铁人赛 Day2 -- SQL到底是什麽东西?讲中文好不好

SQL到底是什麽东西? 全名叫做"结构化查询语言(Structured Query Lan...

Day20_控制项(A15供应者关系)

▉A15 Supplier relationships 供应者关系 └A.15.1 Informat...