vert-x3 / vertx-lang-kotlin

Vert.x for Kotlin
Apache License 2.0
296 stars 68 forks source link

Support for Mutiny for CoroutineVerticle for awaitSuspending Support #229

Closed murphye closed 1 year ago

murphye commented 1 year ago

It would be great to have Mutiny support in this project for CoroutineVerticle as Mutiny is now a preferred Reactive API and has support for Coroutines. This would allow mixing of Reactive APIs with Mutiny with the Coroutines via suspend fun.

Here is some working example code to make it possible to use the io.smallrye.mutiny.coroutines.awaitSuspending with the CoroutineVerticle.

import io.vertx.core.Context
import io.vertx.kotlin.coroutines.CoroutineVerticle
import io.vertx.kotlin.coroutines.dispatcher
import io.vertx.mutiny.core.Vertx
import kotlinx.coroutines.SupervisorJob
import kotlin.coroutines.CoroutineContext

abstract class MutinyCoroutineVerticle : CoroutineVerticle() {

    protected lateinit var vertx: Vertx
    private lateinit var context: Context

    override val coroutineContext: CoroutineContext by lazy { context.dispatcher() + SupervisorJob() }

    override fun init(vertx: io.vertx.core.Vertx, context: Context) {
        this.vertx = Vertx(vertx)
        this.context = context
    }
}

Here is an example of using awaitSuspending().

import io.smallrye.mutiny.coroutines.awaitSuspending
import io.vertx.core.DeploymentOptions
import io.vertx.mutiny.core.Vertx
import kotlin.Array
import kotlin.String

suspend fun main(args: Array<String>) {
    val vertx = Vertx.vertx()
    println("Deployment Starting")
    vertx.deployVerticle({ MainVerticle() }, DeploymentOptions()).awaitSuspending()
    println("Deployment completed")
}

class MainVerticle : MutinyCoroutineVerticle() {
    private var counter = 0L

    override suspend fun start() {

        vertx.periodicStream(2000L)
            .toMulti()
            .subscribe().with { tick -> counter++ }

        vertx.createHttpServer()
                .requestHandler { req -> req.response().endAndForget("@$counter") }
                .listen(8080)
                .awaitSuspending()
   }
}
tsegismont commented 1 year ago

Thanks @murphye for your proposal. I think it could be a nice addition to https://github.com/smallrye/smallrye-mutiny-vertx-bindings (as new module?) cc @jponge