欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

一文彻底搞懂Kotlin中的协程

程序员文章站 2022-07-02 19:37:03
产生背景为了解决异步线程产生的回调地狱//传统回调方式api.login(phone,psd).enquene(new callback(){ public void onsu...

产生背景

为了解决异步线程产生的回调地狱

//传统回调方式
api.login(phone,psd).enquene(new callback<user>(){
 public void onsuccess(user user){
 api.submitaddress(address).enquene(new callback<result>(){
 public void onsuccess(result result){
 ...
 }
 });
 }
});
//使用协程后
val user=api.login(phone,psd)
api.submitaddress(address)
...

协程是什么

本质上,协程是轻量级的线程。

协程关键名词

val job = globalscope.launch {
 delay(1000)
 println("world world!")
}

coroutinescope(作用范围)

控制协程代码块执行的线程,生命周期等,包括globescope、lifecyclescope、viewmodelscope以及其他自定义的coroutinescope

globescope:全局范围,不会自动结束执行

lifecyclescope:生命周期范围,用于activity等有生命周期的组件,在destroyed的时候会自动结束,需额外引入

viewmodelscope:viewmodel范围,用于viewmodel中,在viewmodel被回收时会自动结束,需额外引入

job(作业)

协程的计量单位,相当于一次工作任务,launch方法默认返回一个新的job

suspend(挂起)

作用于方法上,代表该方法是耗时任务,例如上面的delay方法

public suspend fun delay(timemillis: long) {
 ...
}

协程的引入

主框架($coroutines_version替换为最新版本,如1.3.9,下同)

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"

lifecyclescope(可选,版本2.2.0)

implementation 'androidx.activity:activity-ktx:$lifecycle_scope_version'

viewmodelscope(可选,版本2.3.0-beta01)

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$coroutines_viewmodel_version"

简单使用

先举个简单例子

lifecyclescope.launch { 
 delay(2000)
 tvtest.text="test"
}

上面这个例子实现的功能是等待2秒,然后修改id为tvtest的textview控件的text值为test

自定义延迟返回方法

在kotlin里面,对于需要延迟才能返回结果的方法,需要用suspend标明

lifecyclescope.launch {
 val text=gettext()
 tvtest.text = text
}
suspend fun gettext():string{
 delay(2000)
 return "gettext"
}

如果在其他线程,需要使用continuation进行线程切换,可使用suspendcancellablecoroutine 或 suspendcoroutine包裹(前者可取消,相当于后者的扩展),成功调用it.resume(),失败调用it.resumewithexception(exception()),抛出异常

suspend fun gettextinotherthread() = suspendcancellablecoroutine<string> {
 thread {
 thread.sleep(2000)
 it.resume("gettext")
 }
}

异常捕获

协程里面的失败都可以通过异常捕获,来统一处理特殊情况

lifecyclescope.launch {
 try {
 val text=gettext()
 tvtest.text = text
 } catch (e:exception){
 e.printstacktrace()
 }
}

取消功能

下面执行了两个job,第一个是原始的,第二个是在1秒后取消第一个job,这会导致tvtext的文本并不会改变

val job = lifecyclescope.launch {
 try {
 val text=gettext()
 tvtest.text = text
 } catch (e:exception){
 e.printstacktrace()
 }
}
lifecyclescope.launch {
 delay(1000)
 job.cancel()
}

设置超时

这个相当于系统封装了自动取消功能,对应函数withtimeout

lifecyclescope.launch {
 try {
 withtimeout(1000) {
  val text = gettext()
  tvtest.text = text
 }
 } catch (e:exception){
 e.printstacktrace()
 }
}

带返回值的job

与launch类似的还有一个async方法,它会返回一个deferred对象,属于job的扩展类,deferred可以获取返回的结果,具体使用如下

lifecyclescope.launch {
 val one= async {
 delay(1000)
 return@async 1
 }
 val two= async {
 delay(2000)
 return@async 2
 }
 log.i("scope test",(one.await()+two.await()).tostring())
}

高级进阶

自定义coroutinescope

先看coroutinescope源码

public interface coroutinescope {
 public val coroutinecontext: coroutinecontext
}

coroutinescope中主要包含一个coroutinecontext对象,我们要自定义只需实现coroutinecontext的get方法

class testscope() : coroutinescope {
 override val coroutinecontext: coroutinecontext
  get() = todo("not yet implemented")
}

要创建coroutinecontext,得要先知道coroutinecontext是什么,我们再看coroutinecontext源码

/**
 * persistent context for the coroutine. it is an indexed set of [element] instances.
 * an indexed set is a mix between a set and a map.
 * every element in this set has a unique [key].
 */
public interface coroutinecontext {
 public operator fun <e : element> get(key: key<e>): e?
 public fun <r> fold(initial: r, operation: (r, element) -> r): r
 public operator fun plus(context: coroutinecontext): coroutinecontext = 
  ...
 public fun minuskey(key: key<*>): coroutinecontext
 
 public interface key<e : element>
 public interface element : coroutinecontext {
  ...
 }
}

通过注释说明,我们知道它本质就是一个包含element的集合,只是不像set和map集合一样,它自己实现了获取(get),折叠(fold,添加和替换的组合),相减(minuskey,移除),对象组合(plus,如val coroutinecontext=coroutinecontext1+coroutinecontext2)
它的主要内容是element,而element的实现有

  • job 任务
  • continuationinterceptor 拦截器
  • abstractcoroutinecontextelement
  • coroutineexceptionhandler
  • threadcontextelement
  • downstreamexceptionelement
  • ....

可以看到很多地方都有实现element,它主要目的是限制范围以及异常的处理。这里我们先了解两个重要的element,一个是job,一个是coroutinedispatcher
job

  • job:子job取消,会导致父job和其他子job被取消;父job取消,所有子job被取消
  • supervisorjob:父job取消,所有子job被取消

coroutinedispatcher

  • dispatchers.main:主线程执行
  • dispatchers.io:io线程执行

我们模拟一个类似lifecyclescope的自定义testscope

class testscope() : coroutinescope {
 override val coroutinecontext: coroutinecontext
  get() = supervisorjob() +dispatchers.main
}

这里我们定义了一个总流程线supervisorjob()以及具体执行环境dispatchers.main(android主线程),假如我们想替换掉activity的lifecyclescope,就需要在activity中创建实例

val testscope=testscope()

然后在activity销毁的时候取消掉所有job

override fun ondestroy() {
 testscope.cancel()
 super.ondestroy()
}

其他使用方式同lifecyclescope,如

testscope.launch{
 val text = gettext()
 tvtest.text = text
}

深入理解job

coroutinescope中包含一个主job,之后调用的launch或其他方法创建的job都属于coroutinescope的子job,每个job都有属于自己的状态,其中包括isactive、iscompleted、iscancelled,以及一些基础操作start()、cancel()、join(),具体的转换流程如下

一文彻底搞懂Kotlin中的协程

我们先从创建job开始,当调用launch的时候默认有三个参数coroutinecontext、coroutinestart以及代码块参数。

  • context:coroutinecontext的对象,默认为coroutinestart.default,会与coroutinescope的context进行折叠
  • start:coroutinestart的对象,默认为coroutinestart.default,代表立即执行,同时还有coroutinestart.lazy,代表非立即执行,必须调用job的start()才会开始执行
val job2= lifecyclescope.launch(start = coroutinestart.lazy) {
 delay(2000)
 log.i("scope test","lazy")
}
job2.start()

当使用这种模式创建时默认就是new状态,此时isactive,iscompleted,iscancelled都为false,当调用start后,转换为active状态,其中只有isactive为true,如果它的任务完成了则会进入completing状态,此时为等待子job完成,这种状态下还是只有isactive为true,如果所有子job也完成了则会进入completed状态,只有iscompleted为true。如果在active或completing状态下出现取消或异常,则会进入cancelling状态,如果需要取消父job和其他子job则会等待它们取消完成,此时只有iscancelled为true,取消完成后最终进入cancelled状态,iscancelled和iscompleted都为true

state isactive iscompleted iscancelled
new false false false
active true false false
completing true false false
cancelling false false true
cancelled false true true
completed false true false

不同job交互需使用join()与cancelandjoin()

  • join():将当前job添加到其他协程任务里面
  • cancelandjoin():取消操作,只是添加进去后再取消
val job1= globlescope.launch(start = coroutinestart.lazy) {
 delay(2000)
 log.i("scope test","job1")
}
lifecyclescope.launch {
 job1.join()
 delay(2000)
 log.i("scope test","job2")
}

深入理解suspend

suspend作为kotlin新增的方法修饰词,最终实现还是java,我们先看它们的差异性

suspend fun test1(){}
fun test2(){}

对应java代码

public final object test1(@notnull continuation $completion) {
 return unit.instance;
}
public final void test2() {
}

对应字节码

public final test1(lkotlin/coroutines/continuation;)ljava/lang/object;
 ...
 l0
 linenumber 6 l0
 getstatic kotlin/unit.instance : lkotlin/unit;
 areturn
 l1
 localvariable this lcom/lieni/android_c/ui/test/testactivity; l0 l1 0
 localvariable $completion lkotlin/coroutines/continuation; l0 l1 1
 maxstack = 1
 maxlocals = 2

public final test2()v
 l0
 linenumber 9 l0
 return
 l1
 localvariable this lcom/lieni/android_c/ui/test/testactivity; l0 l1 0
 maxstack = 0
 maxlocals = 1

可以看到,加了suspend的方法其实和普通方法一样,只是传入时多了个continuation对象,并返回了unit.instance对象

public interface continuation<in t> {
  public val context: coroutinecontext
  public fun resumewith(result: result<t>)
}

而continuation的具体实现在basecontinuationimpl中

internal abstract class basecontinuationimpl(...) : continuation<any?>, coroutinestackframe, serializable {
  public final override fun resumewith(result: result<any?>) {
    ...
    while (true) {
      ...
      with(current) {
       	val outcome = invokesuspend(param)
        ...
        releaseintercepted() 
        if (completion is basecontinuationimpl) {
          ...
        } else {
          ...
          return
        }
      }
    }
  }
  ...
}

当我们调用resumewith时,它会一直执行一个循环,调用invokesuspend(param)和releaseintercepted() ,直到最顶层completion执行完成后返回,并且释放协程的interceptor

最终的释放在continuationimpl中实现

internal abstract class continuationimpl(...) : basecontinuationimpl(completion) {
  ...
  protected override fun releaseintercepted() {
    val intercepted = intercepted
    if (intercepted != null && intercepted !== this) {
      context[continuationinterceptor]!!.releaseinterceptedcontinuation(intercepted)
    }
    this.intercepted = completedcontinuation 
  }
}

通过这里知释放最终通过coroutinecontext中为continuationinterceptor的element来实现
而暂停也是同理,继续看suspendcoroutine

public suspend inline fun <t> suspendcoroutine(crossinline block: (continuation<t>) -> unit): t =
  suspendcoroutineuninterceptedorreturn { c: continuation<t> ->
    val safe = safecontinuation(c.intercepted())
    ...
  }

默认会调用continuation的intercepted()方法

internal abstract class continuationimpl(...) : basecontinuationimpl(completion) {
  ...
  public fun intercepted(): continuation<any?> =intercepted
      ?: (context[continuationinterceptor]?.interceptcontinuation(this) ?: this)
        .also { intercepted = it }
}

可以看到暂停最终也是通过coroutinecontext中为continuationinterceptor的element来实现

流程总结(线程切换)

  • 创建新的continuation
  • 调用coroutinescope中的context的continuationinterceptor的interceptcontinuation方法暂停父任务
  • 执行子任务(如果指定了线程,则在新线程执行,并传入continuation对象)
  • 执行完毕后用户调用continuation的resume或者resumewith返回结果
  • 调用coroutinescope中的context的continuationinterceptor的releaseinterceptedcontinuation方法恢复父任务

阻塞与非阻塞

coroutinescope默认是不会阻塞当前线程的,如果需要阻塞可以使用runblocking,如果在主线程执行下面代码,会出现2s白屏

runblocking { 
  delay(2000)
  log.i("scope test","runblocking is completed")
}

阻塞原理:执行runblocking默认会创建blockingcoroutine,而blockingcoroutine中会一直执行一个循环,直到当前job为iscompleted状态才会跳出循环

public fun <t> runblocking(...): t {
  ...
  val coroutine = blockingcoroutine<t>(newcontext, currentthread, eventloop)
  coroutine.start(coroutinestart.default, coroutine, block)
  return coroutine.joinblocking()
}
private class blockingcoroutine<t>(...) : abstractcoroutine<t>(parentcontext, true) {
  ...
  fun joinblocking(): t {
   ...
   while (true) {
    ...
    if (iscompleted) break
    ...
   }  
   ...
  }
}

总结

到此这篇关于一文彻底搞懂kotlin中协程的文章就介绍到这了,更多相关kotlin协程内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: kotlin 协程