All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.resilience4j.ratelimiter.operator.RateLimiterObserver Maven / Gradle / Ivy

Go to download

Resilience4j is a lightweight, easy-to-use fault tolerance library designed for Java8 and functional programming

There is a newer version: 2.2.0
Show newest version
package io.github.resilience4j.ratelimiter.operator;

import static java.util.Objects.requireNonNull;

import java.util.concurrent.atomic.AtomicBoolean;

import io.github.resilience4j.ratelimiter.RateLimiter;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * A RxJava {@link Observer} to protect another observer by a {@link RateLimiter}.
 * Consumes one permit when subscribed and one permit per emitted event except the first one.
 *
 * @param  the value type of the upstream and downstream
 */
final class RateLimiterObserver extends DisposableRateLimiter implements Observer {
    private final Observer childObserver;
    private final AtomicBoolean firstEvent = new AtomicBoolean(true);

    RateLimiterObserver(RateLimiter rateLimiter, Observer childObserver) {
        super(rateLimiter);
        this.childObserver = requireNonNull(childObserver);
    }

    @Override
    public void onSubscribe(Disposable disposable) {
        onSubscribeWithPermit(disposable);
    }

    @Override
    protected void onSubscribeInner(Disposable disposable) {
        childObserver.onSubscribe(disposable);
    }

    @Override
    public void onNext(T value) {
        onNextInner(value, firstEvent.getAndSet(false));
    }

    @Override
    protected void permittedOnNext(T value) {
        childObserver.onNext(value);
    }

    @Override
    public void onComplete() {
        onCompleteInner();
    }

    @Override
    protected void permittedOnComplete() {
        childObserver.onComplete();
    }

    @Override
    public void onError(Throwable e) {
        onErrorInner(e);
    }

    @Override
    protected void permittedOnError(Throwable e) {
        childObserver.onError(e);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy