android开发分享Kotlin协程的启动方式介绍

启动协程的基本方式1.globalscope.launch代码示例:fun testglobalscope() { globalscope.launch { println(“co

启动协程的基本方式

上述就是android开发分享Kotlin协程的启动方式介绍的全部内容,如果对大家有所用处且需要了解更多关于Android学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

1.globalscope.launch

代码示例:

fun testglobalscope() {      globalscope.launch {          println("coroutinue started!")          delay(1000l)          println("hello world!")      }      println("after launch!")      thread.sleep(2000l)      println("process end!")  }  /**   * after launch!   * coroutinue started!   * hello world!   * process end!   */
@delicatecoroutinesapi  public object globalscope : coroutinescope {      /**       * returns [emptycoroutinecontext].       */      override val coroutinecontext: coroutinecontext          get() = emptycoroutinecontext  }
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  }

launch函数是coroutinescope的扩展函数,它有三个参数:

  • context: coroutinecontext = emptycoroutinecontext, 第一个参数是协程上下文,它的默认值是 emptycoroutinecontext,如果不传这个参数,默认就会使用 emptycoroutinecontext。也可以传入 kotlin 官方为我们提供的 dispatchers,来指定协程运行的线程池。(dispatchers.io、dispatchers.unconfined、dispatchers.main)
  • start: coroutinestart = coroutinestart.default,第二个参数是协程的启动模式,默认值是coroutinestart.default,coroutinestart 是一个枚举类,一共有:default、lazy、atomic、undispatched。
  • block: suspend coroutinescope.() -> unit,第三个参数是函数类型block,它的类型是suspend coroutinescope.() -> unit。本质是一个挂起函数。
  • 函数的返回值是一个 job,它其实代表的是协程的句柄,并不能返回协程的执行结果。

2.runblocking 启动协程

代码示例

fun testrunblocking2() {      runblocking {          println("coroutinue started!")          delay(1000l)          println("hello world!")      }      println("after launch")      thread.sleep(2000l)      println("process end")  }  /**   * coroutinue started!   * hello world!   * after launch   * process end   */
@throws(interruptedexception::class)  public actual fun <t> runblocking(context: coroutinecontext, block: suspend coroutinescope.() -> t): t {      contract {          callsinplace(block, invocationkind.exactly_once)      }      val currentthread = thread.currentthread()      val contextinterceptor = context[continuationinterceptor]      val eventloop: eventloop?      val newcontext: coroutinecontext      if (contextinterceptor == null) {          // create or use private event loop if no dispatcher is specified          eventloop = threadlocaleventloop.eventloop          newcontext = globalscope.newcoroutinecontext(context + eventloop)      } else {          // see if context's interceptor is an event loop that we shall use (to support testcontext)          // or take an existing thread-local event loop if present to avoid blocking it (but don't create one)          eventloop = (contextinterceptor as? eventloop)?.takeif { it.shouldbeprocessedfromcontext() }              ?: threadlocaleventloop.currentornull()          newcontext = globalscope.newcoroutinecontext(context)      }      val coroutine = blockingcoroutine<t>(newcontext, currentthread, eventloop)      coroutine.start(coroutinestart.default, coroutine, block)      return coroutine.joinblocking()  }

runblocking是普通函数,第一个参数:context: coroutinecontext,协程上下文。第二个参数是函数类型,block: suspend coroutinescope.() -> t,函数类型是有返回值类型 t 的,与 runblocking 的返回值类型是一样的,runblocking 其实是可以从协程当中返回执行结果的。

fun testrunblocking() {      val runblockingresult = runblocking {          delay(500l)          return@runblocking "haha"      }      println("result:$runblockingresult")  }  result:haha

runblocking特点:

runblocking 启动的协程会阻塞当前线程的执行。

3.async启动协程

使用 async{} 创建协程,可以通过它返回的deferred拿到协程的执行结果。

代码示例

fun testasync() {      runblocking {          val deferred = async {              println("do async:${thread.currentthread().name}")              delay(1000l)              return@async "do completed"          }          println("after async:${thread.currentthread().name}")          val result = deferred.await()          println("result is: $result")      }  }  after async:main @coroutine#1  do async:main @coroutine#2  result is: do completed
public fun <t> coroutinescope.async(      context: coroutinecontext = emptycoroutinecontext,      start: coroutinestart = coroutinestart.default,      block: suspend coroutinescope.() -> t  ): deferred<t> {      val newcontext = newcoroutinecontext(context)      val coroutine = if (start.islazy)          lazydeferredcoroutine(newcontext, block) else          deferredcoroutine<t>(newcontext, active = true)      coroutine.start(start, coroutine, block)      return coroutine  }

async注意点

  • async 启动协程以后,不会阻塞当前程序的执行流程。
  • async{}的返回值,是一个 deferred 对象,它的 await() 方法,就可以拿到协程的执行结果。
  • await只是等待执行完,并不是触发执行。

到此这篇关于kotlin协程的启动方式介绍的文章就介绍到这了,更多相关kotlin协程启动内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/addevelopment/1237398.html

(0)
上一篇 2022年9月8日
下一篇 2022年9月8日

精彩推荐