What is the correct way to convert a Kotlin suspend function to a function returning Mono?

Viewed 1193

Let's say we have a function

suspend fun doSomething(value: Int): String {
    delay(1000L)
    return "abc_$value"
}

How to convert it to a function returning Mono? Are there any hidden problems with switching between threads belonging to coroutine scope and reactor event loop threads?

fun resultAsMono(fn: suspend (Int) -> String): (Int) -> Mono<String> {
   // ???
}

So that effect would be like this:

val newFn = resultAsMono(::doSomething)

val result = newFn(5).block()

assertThat(result).isEqualTo("abc_5")
1 Answers

A function already exists for this conversion. You need this dependency...

<dependency>
    <groupId>org.jetbrains.kotlinx</groupId>
    <artifactId>kotlinx-coroutines-reactor</artifactId>
    <version>1.6.0</version>
</dependency>

...and then you can do the following:

import kotlinx.coroutines.delay
import kotlinx.coroutines.reactor.mono

fun main() {
    val mono = mono { doSomething(5) }
    val result = mono.block()
    println(result)
}

suspend fun doSomething(value: Int): String {
    delay(1000L)
    return "abc_$value"
}

In terms of threading you have nothing to worry about. Reactor is concurrency agnostic, so it can work with Kotlin coroutines threads just fine.

Related