Skip to content

Kotlin coroutines integration#

The module mutiny-kotlin provides an integration with Kotlin coroutines.

There are currently four extension methods available for converting between Mutiny and Kotlin coroutine types offered in a separate package. For implementation details please have also a look to these methods documentation.

Dependency coordinates#

The extension functions are shipped in the package io.smallrye.mutiny.coroutines:

1
2
3
4
import io.smallrye.mutiny.coroutines.asFlow
import io.smallrye.mutiny.coroutines.asMulti
import io.smallrye.mutiny.coroutines.asUni
import io.smallrye.mutiny.coroutines.awaitSuspending

You need to add the following dependency to your project:

<dependency>
    <groupId>io.smallrye.reactive</groupId>
    <artifactId>mutiny-kotlin</artifactId>
    <version>1.6.0</version>
</dependency>
implementation("io.smallrye.reactive:mutiny-kotlin:1.6.0")
implementation "io.smallrye.reactive:mutiny-kotlin:1.6.0"

Awaiting a Uni in coroutines#

Within a coroutine or suspend function you can easily await Uni events in a suspended way:

1
2
3
4
5
6
7
val uni: Uni<String> = Uni.createFrom().item("Mutiny ❤ Kotlin")
try {
    // Available within suspend function and CoroutineScope
    val item: String = uni.awaitSuspending()
} catch (failure: Throwable) {
    // onFailure event happened
}

Processing a Multi as Flow#

The coroutine Flow type matches Multi semantically, even though it isn’t a feature complete reactive streams implementation. You can process a Multi as Flow as follows:

val multi: Multi<String> = Multi.createFrom().items("Mutiny", "❤", "Kotlin")
val flow: Flow<String> = multi.asFlow()

Providing a Deferred value as Uni#

The other way around is also possible, let a Deferred become a Uni:

val deferred: Deferred<String> = GlobalScope.async { "Kotlin ❤ Mutiny" }
val uni: Uni<String> = deferred.asUni()

Creating a Multi from a Flow#

Finally, creating a Multi from a Flow is also possible:

val flow: Flow<String> = flowOf("Kotlin", "❤", "Mutiny")
val multi: Multi<String> = flow.asMulti()