Android项目过程中,看到了Anko库的异步框架doAsync()与uiThread()方法,然而Anko库已经被废弃了,目前来说Kotlin协程会是更好的异步解决方案,但我作为初学者还是去了解了一下其实现原理和源码,如有错误理解,欢迎批评指正。
a. doAsync是如何使用的?
doAsync{
运行耗时的后台任务
uiThread{
需要在主线程执行的任务
}
}
这里的doAsync{…},我们实际上调用的是 doAsync扩展函数,其源代码如下
fun <T> T.doAsync(
exceptionHandler: ((Throwable) -> Unit)? = null,
task: AnkoAsyncContext<T>.() -> Unit
): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr) ?: Unit
}
}
}
doAsync接收两个参数:
- 异常情况下的exceptionHandler,默认值为null
- 需要在异步环境下运行的函数(代码块),这里的AnkoAsyncContext的实际用途后续会说到。
doAsync的返回类型是Future
Future类在Kotlin官方文档中的解释如下,即,一个用于表达抽象计算的类,其结果可能在未来变得可获取。
Class representing abstract computation, whose result may become available in the future.<