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

1

7

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")
Monolith answered 21/1, 2022 at 10:36 Comment(0)
D
10

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.

Davey answered 22/1, 2022 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.