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

Android结合kotlin使用coroutine的方法实例

程序员文章站 2022-03-09 19:52:56
最近入了android坑,目前还处于疯狂学习的状态,所以很久都没有写博客了。今天记录一个小代码片段,在android上使用coroutine 的小例子。由于我自己是做一个记账软件来学习的,我用了grp...

最近入了android坑,目前还处于疯狂学习的状态,所以很久都没有写博客了。今天记录一个小代码片段,在android上使用coroutine 的小例子。

由于我自己是做一个记账软件来学习的,我用了grpc,最开始我是使用线程来做网络请求的:

thread {
 // 网络请求代码

 runonuithread {
  // 更新ui的代码
 }
}

今天把这一套全部重写成用coroutine。

首先coroutine得有个调度器,英文叫做 “dispatchers”,有这么几个:

  • dispatchers.main 这里面的coroutine跑在主线程上,在android里也就是ui线程,所以如果在这里面的coroutine也执行大量耗时代码的话,也是会卡ui的
  • dispatchers.io 用来跑大io的
  • dispatchers.default 用来跑高cpu消耗的
  • dispatchers.unconfined 不绑定在任何特定执行线程上

然后,为了多个coroutine之间可以分组啊,就像进程里可以放很多线程那样,又搞了一个概念,叫做 scope,默认有一个全局scope,叫做 globalscope,全局的, 就和全局变量一样,在android上,这个里面跑的coroutine,生命周期和app一样久,不推荐在这里起coroutine。

推荐的方式是每个activity里起一个scope,然后再launch。

所以我就这样写基类:

abstract class baseactivity : appcompatactivity(), coroutinescope {
 /*
 默认的coroutine scope是main,也就是ui线程(主线程)。如果要做io,比如网络请求,记得
 包裹在 launch(dispatchers.io) {} 里,如果要大量计算,包裹在 launch(dispatcher.default) {} 里
 或者直接写 launch。 ui操作则用 withcontext(dispatchers.main) {} 切回来
  */
 private val job = supervisorjob()
 override val coroutinecontext: coroutinecontext
  get() = dispatchers.main + job

 override fun ondestroy() {
  super.ondestroy()
  coroutinecontext.cancelchildren()
 }

这样子之后,就可以直接launch,起coroutine了:

launch {
 val req = createfeedbackreq.newbuilder().build()
 val respany = callrpc {
  api.createfeedback(req)
 }
 respany?:return@launch

 val resp = respany as createfeedbackresp
 if (handlerespaction(resp.action)) {
  withcontext(dispatchers.main) {
   showsnackbar(r.string.thank_you_for_feedback)
   delay(1000)
   finish()
  }
 }
}

如上,默认情况下,root coroutine就是当前所在activity,而他们默认会在 dispatchers.main 上执行,如果想要coroutine在 别的 dispatcher 上执行,就用 withcontext,然后里面如果又想更新ui的话,就用 withcontext(dispatchers.main)。

那为啥 launch 不传参数的话,就是直接用的 dispatchers.main 呢?因为其实 coroutinescope 是一个接口,而 coroutinecontext 是里面的一个变量:

public interface coroutinescope {
 /**
  * the context of this scope.
  * context is encapsulated by the scope and used for implementation of coroutine builders that are extensions on the scope.
  * accessing this property in general code is not recommended for any purposes except accessing the [job] instance for advanced usages.
  *
  * by convention, should contain an instance of a [job][job] to enforce structured concurrency.
  */
 public val coroutinecontext: coroutinecontext
}

我们再来看看 launch 的实现:

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
}

@experimentalcoroutinesapi
public actual fun coroutinescope.newcoroutinecontext(context: coroutinecontext): coroutinecontext {
 val combined = coroutinecontext + context
 val debug = if (debug) combined + coroutineid(coroutine_id.incrementandget()) else combined
 return if (combined !== dispatchers.default && combined[continuationinterceptor] == null)
  debug + dispatchers.default else debug
}

可以看到,默认情况下,会把当前的 coroutinecontext 放在前面。

kotlin的coroutine很好用,不过我感觉还是有点复杂,我也还在学习。

ref:

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/index.html

到此这篇关于android结合kotlin使用coroutine的文章就介绍到这了,更多相关android结合kotlin使用coroutine内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!