kotlinx.coroutines
Three libraries built upon Kotlin coroutines:
kotlinx-coroutines-asyncwith convenient interfaces/wrappers to commonly used asynchronous API shipped with standard JDK, namely promise-likeCompletableFutureand asynchronous channels fromjava.niopackagekotlinx-coroutines-generateprovides ability to createSequenceobjects generated by coroutine body containingyieldsuspension pointskotlinx-coroutines-rxallows to useObservableobjects from RxJava inside a coroutine body to suspend on them
Examples
Async
import kotlinx.coroutines.async
import java.util.concurrent.CompletableFuture
private fun startLongAsyncOperation(v: Int) =
CompletableFuture.supplyAsync {
Thread.sleep(1000)
"Result: $v"
}
fun main(args: Array<String>) {
val future = async {
(1..5).map {
startLongAsyncOperation(it).await()
}.joinToString("\n")
}
println(future.get())
}Bear in mind that async library actively uses CompletableFuture from JDK 8, so
it will not work with earlier versions.
Generate
import kotlinx.coroutines.generate
fun main(args: Array<String>) {
val sequence = generate {
for (i in 1..5) {
yield(i)
}
}
println(sequence.joinToString(" "))
}RxJava
import kotlinx.coroutines.asyncRx
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import rx.Observable
interface GitHub {
@GET("orgs/{user}/repos")
fun orgRepos(@Path("user") user: String): Observable<List<Repo>>
}
data class Repo(val name: String)
fun main(args: Array<String>) {
val retrofit = Retrofit.Builder().apply {
baseUrl("https://api.github.com")
addConverterFactory(GsonConverterFactory.create())
addCallAdapterFactory(RxJavaCallAdapterFactory.create())
}.build()
val github = retrofit.create(GitHub::class.java)
asyncRx {
for (org in listOf("Kotlin", "ReactiveX")) {
// `awaitSingle()` call here is a suspension point,
// i.e. coroutine's code stops on it until request is not completed
val repos = github.orgRepos(org).take(5).awaitSingle().joinToString()
println("$org: $repos")
}
}
}For more examples you can look at kotlinx-coroutines-async-example-ui
and kotlinx-coroutines-rx-example samples projects or in tests directories.
Using in your projects
Note that these libraries are experimental and are subject to change.
The libraries are published to kotlin-eap-1.1 bintray repository.
These libraries require kotlin compiler version to be at least 1.1-M04 and
require kotlin runtime of the same version as a dependency, which can be obtained from the same repository.
Maven
Add the bintray repository to <repositories> section (and also add pluginRepository to <pluginRepositories>,
if you're willing to get kotlin-maven-plugin from there):
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>dl</id>
<name>bintray</name>
<url>http://dl.bintray.com/kotlin/kotlin-eap-1.1</url>
</repository>Add dependencies (you can add just those of them that you need):
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-generate</artifactId>
<version>0.2-beta</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-async</artifactId>
<version>0.2-beta</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-rx</artifactId>
<version>0.2-beta</version>
</dependency>Gradle
Add the bintray repository (and also add it to buildScript section, if you're willing to get kotlin-gradle-plugin from there):
repositories {
maven {
url "http://dl.bintray.com/kotlin/kotlin-eap-1.1"
}
}Add dependencies (you can add just those of them that you need):
compile 'org.jetbrains.kotlinx:kotlinx-coroutines-generate:0.2-beta'
compile 'org.jetbrains.kotlinx:kotlinx-coroutines-async:0.2-beta'
compile 'org.jetbrains.kotlinx:kotlinx-coroutines-rx:0.2-beta'NB: As async library is built upon CompletableFuture it requires JDK 8 (24 Android API level)