This repository has been archived by the owner on Jul 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Anko Coroutines
itrofimov-iv edited this page Nov 11, 2018
·
11 revisions
Add the anko-coroutines
dependency to your build.gradle
:
dependencies {
implementation "org.jetbrains.anko:anko-coroutines:$anko_version"
}
If your asynchronous API does not support cancellation, your coroutine may be suspended for an indefinite time period. As a coroutine holds the strong references to captured objects, capturing the instance of Activity
or Fragment
instance may cause a memory leak.
Use asReference()
in such cases instead of the direct capturing. (Please note that Anko's method async
is considered deprecated, so as to not conflict with the kotlinx.coroutines
function by the same name. Use doAsync
instead.)
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(data)
}
}
fun showData(data: Data) { ... }
}
Please note that the bg
function is deprecated, as well as Anko's doAsync
function demonstrated in this example.
You can easily execute your code on the background thread using bg()
:
fun getData(): Data { ... }
fun showData(data: Data) { ... }
doAsync(UI) {
val data: Deferred<Data> = bg {
// Runs in background
getData()
}
// This code is executed on the UI thread
showData(data.await())
}