Resilience4j: Allow suspending functions in EventPublisherEvent handlers

Created on 21 Oct 2019  路  6Comments  路  Source: resilience4j/resilience4j

Would be nice to be able to do something lie this

fun main() {
    runBlocking {
        val retry = Retry.of(
            "test-retry", custom<Any>()
                .maxAttempts(4)
                .retryExceptions(SomeException::class.java)
                .waitDuration(Duration.ofMillis(1000))
                .build()
        )

        retry.eventPublisher.onRetry { println("Retry happened $it"); cleanupBeforeRetry() }
        val i2 = retry.executeSuspendFunction { doSomething() }
        print(i2)
    }
}

suspend fun cleanupBeforeRetry() {
    delay(10)
    println("Cleanup ")
}
var i = 0
suspend fun doSomething(): Any {
    println("Trying")
    delay(100)
    if (i < 4) {
        throw SomeException("asdf")
    }
    return i
}

question

All 6 comments

Hi,
could you use Kotlin Flows?
I would usually recommend to convert the stream of events into a reactive stream with RxJava2 or Reactor. Then you can define the scheduler which you would like to use to process the events asynchronously.

I will try Kotlin flows, but it seems it is not released yet.

Let me try your suggestion

The core of Resilience4j doesn't use Kotlin. I can't change the internal event processor.
But could you add extension functions?
Like here? -> https://github.com/resilience4j/resilience4j/blob/master/resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/circuitbreaker/CircuitBreaker.kt

Sure syntactically not a problem, semantically I am not familiar enough with the code base, to decide whether it will work properly :) but I will give it a try

If it works, it would be an interesting PR :)

I mean since it's java there are 2 ways to do it, either
fun Retry.EventPublisher.awaitOnError(eventConsumer: suspend (RetryOnErrorEvent) -> Unit) = onError { runBlocking { eventConsumer(it) } }

or modify the Core code and convert co-routines to CompletableFutures and let the EventProcessor deal with it

Was this page helpful?
0 / 5 - 0 ratings