A Kotlin library for Android allowing writing asynchronous code in synchronous style using async
/await
approach
async {
progressBar.visibility = View.VISIBLE
// Release main thread and wait until text is loaded in background thread
val loadedText = await { loadFromServer() }
// Loaded successfully, come back in UI thread and show the result
txtResult.text = loadedText
progressBar.visibility = View.INVISIBLE
}
The point is that you can write asynchronous code in a simple imperative style. Calling await
to run code in background doesn't lock UI thread. Then execution continues in UI thread after background work is finished. There is no magic, see how it works.
Coroutine code has to be passed as a lambda in async
function
async {
// Coroutine body
}
Long running code has to be passed as a lambda in await
function
async {
val result = await {
//Long running code
}
// Use result
}
You may have many await
calls inside async
block, or have await
in a loop
async {
val repos = await { github.getRepos() }
showList(repos)
repos.forEach { repo ->
val stats = await { github.getStats(repo.name) }
showStats(repo, stats)
}
}
Use it to show loading progress, its second parameter is a progress handler.
val loadedText = awaitWithProgress(::loadTextWithProgress) {
// Called in UI thread
progressBar.progress = it
progressBar.max = 100
}
A data loading function (like the loadTextWithProgress
above) should has a functional parameter of type (P) -> Unit
which can be called in order to push progress value. For example, it could be like:
private fun loadTextWithProgress(handleProgress: (Int) -> Unit): String {
for (i in 1..10) {
handleProgress(i * 100 / 10) // in %
Thread.sleep(300)
}
return "Loaded Text"
}
async {
try {
val loadedText = await {
// throw exception in background thread
}
// Process loaded text
} catch (e: Exception) {
// Handle exception in UI thread
}
}
Using onError
can be more convenient because resulting code has fewer indents. onError
, when defined, has more priority than try/catch
.
async {
val loadedText = await {
// throw exception in background thread
}
// Process loaded text
}.onError {
// Handle exception in UI thread
}
The library has Activity.async
and Fragment.async
extension functions to produce more safe code. So when using async
inside Activity/Fragment, coroutine won't be resumed if Activity
is in finishing state or Fragment
is detached.
The library has a convenient API to work with Retrofit and rxJava.
await(retrofit2.Call)
reposResponse = await(github.listRepos(userName))
awaitSuccessful(retrofit2.Call)
Returns Response<V>.body()
if successful, or throws RetrofitHttpError
with error response otherwise.
reposList = awaitSuccessful(github.listRepos(userName))
- await(Observable)
Waits until observable
emits first value.
async {
val observable = Observable.just("O")
result = await(observable)
}
###How to create custom extensions
You can create your own await
implementations. Here is example to give you idea
suspend fun <V> AsyncController.await(observable: Observable<V>, machine: Continuation<V>) {
this.await({ observable.toBlocking().first() }, machine)
}
##How it works
The library is built upon coroutines introduced in Kotlin 1.1.
The Kotlin compiler responsibility is to convert coroutine (everything inside async
block) into a state machine, where every await
call is non-blocking suspension point. The library is responsible for thread handling and managing state machine. When background computation is done the library delivers result back into UI thread and resumes coroutine execution.
Add library dependency into your app's build.gradle
compile 'co.metalab.asyncawait:asyncawait:0.5'
As for now Kotlin 1.1 is not released yet, you have to download and setup latest Early Access Preview release.
- Go to
Tools
->Kotlin
->Configure Kotlin Plugin updates
->Select EAP 1.1
->Check for updates
and install latest one. - Make sure you have similar config in the main
build.gradle
buildscript {
ext.kotlin_version = '1.1-M01'
repositories {
...
maven {
url "http://dl.bintray.com/kotlin/kotlin-eap-1.1"
}
}
dependencies {
// (!) 2.1.2 This version is more stable with Kotlin for now
classpath 'com.android.tools.build:gradle:2.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
- Make sure you have similar config in app's
build.gradle
buildscript {
repositories {
...
maven {
url "http://dl.bintray.com/kotlin/kotlin-eap-1.1"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
and this section for getting latest kotlin-stdlib
repositories {
mavenCentral()
maven {
url "http://dl.bintray.com/kotlin/kotlin-eap-1.1"
}
}