2

I need to perform some action immediately after Retry is successful for server-sent event implementation, I was unable to find any method in reactor.util.retry.Retry. Is there any other alternate to do doOnRetrySuccess(func)

Arun Kumar V
  • 309
  • 3
  • 4
  • 11

1 Answers1

2

I'm not aware of a built-in operator to do this, but you could utilize an AtomicBoolean to detect if the onNext/onComplete signal occurs immediately after a retry:

final AtomicBoolean retrying = new AtomicBoolean();

monoOrFlux
        .retryWhen(Retry
                // Configure whatever retry behavior you want here.
                // For simplicity, this example uses .indefinitely()
                .indefinitely()
                // Set the retrying flag to indicate that a retry is being attempted.
                .doBeforeRetry(signal -> retrying.set(true)))
        // Check and reset the retrying flag in doOnEach.
        // This example uses doOnEach, which works for both Mono and Flux.
        // If the stream is a Mono, then you could simplify this to use doOnSuccess instead.
        .doOnEach(signal -> {
            if ((signal.isOnNext() || signal.isOnComplete())
                    && retrying.compareAndSet(true, false)) {
                // This is the first onNext signal emitted after a retry,
                // or the onComplete signal (if no element was emitted) after a retry.
            }
        });
Phil Clay
  • 4,028
  • 17
  • 22
  • Thank you for this but I am consuming server-sent events (https://www.baeldung.com/spring-server-sent-events) and doOnEach is not called as soon as retry is successful, It is only called when there is an event after successful retry. – Arun Kumar V Jun 14 '21 at 06:52
  • you could use a similar approach with a `doOnSubscribe` BUT placed before `retryWhen`. You'd need the atomic(boolean|integer) to detect the first subscription (which is the original non-retry one) vs subsequent subscriptions (which are, likely, retries). you might need to wrap both the atomic and Flux in a `defer` to ensure atomic is not sharing state between multiple subscribers – Simon Baslé Jun 14 '21 at 09:41