anko
目录
在你的项目中使用Anko协程
添加anko-coroutines
到你的build.gradle
:
1 2 3
| dependencies { compile "org.jetbrains.anko:anko-coroutines:$anko_version" }
|
Listener助手
asReference()
如果您的异步API不支持取消,你的协程可能会被无限期挂起。
由于协程持有对被捕获对象的强引用,捕获的Activity或Fragment实例可能会导致内存泄漏。
在这种情况下使用asReference()而不是直接捕获:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| suspend fun getData(): Data { ... }
class MyActivity : Activity() { fun loadAndShowData() { // Ref<T> uses the WeakReference under the hood val ref: Ref<MyActivity> = this.asReference()
async(UI) { val data = getData() // Use ref() instead of this@MyActivity ref().showData() } }
fun showData(data: Data) { ... } }
|
bg()
您可以使用bg()
轻松地在后台线程上执行您的代码:
1 2 3 4 5 6 7 8 9 10 11 12
| fun getData(): Data { ... } fun showData(data: Data) { ... }
async(UI) { val data: Deferred<Data> = bg { // 运行在后台 getData() }
// 该代码在UI线程上执行 showData(data.await()) }
|