Alex Schiff
01/03/2024, 2:00 PM@Bean
suspend fun myConvertedJavaConsumer = Consumer<String> {
mySuspendFunction(it)
}
The above code is giving me an error, Suspension functions can be called only within coroutine body
. I am trying to convert a Java consumer to a Kotlin coroutine and I'm unsure how to proceed. This is using spring-cloud-stream
and spring-cloud-funciton-kotlin
librariesross_a
01/03/2024, 2:19 PMross_a
01/03/2024, 2:28 PMsuspendCoroutine
If the consumer is to be called more than once, use callbackFlow
ross_a
01/03/2024, 2:32 PMclass Library {
fun attachCallback(consumer: Consumer<String>) {
consumer.accept("hey")
}
fun attachListener(consumer: Consumer<String>) {
consumer.accept("hey")
consumer.accept("hola")
}
fun removeListener(consumer: Consumer<String>) {
TODO()
}
}
fun thing() = runBlocking {
lateinit var library: Library
val result = suspendCoroutine { continuation ->
library.attachCallback { continuation.resume(it) }
}
val results = callbackFlow {
val consumer: (t: String) -> Unit = { trySendBlocking(it) }
library.attachListener(consumer)
awaitClose { library.removeListener(consumer) }
}.toList()
}
Alex Schiff
01/03/2024, 3:16 PMspring-cloud-function-kotlin
library) then wrapping it in a coroutineScope.launch
. not sure if this is the best approach or notross_a
01/03/2024, 3:20 PMConsumer<String> {
runBlocking {
mySuspendFunction(it)
}
}
which will block on the original threadross_a
01/03/2024, 3:27 PMspring-cloud-funciton-kotlin
) it looks like suspending functions may be natively supported. Perhaps try:
@Bean
fun myConvertedJavaConsumer(): suspend (String) -> Unit {
mySuspendFunction(it)
}
Alex Schiff
01/03/2024, 3:58 PM