如何过度调用ReactiveX onSubscribe请求

时间:2015-09-08 08:22:21

标签: rx-java rx-android

我有一个执行耗时的网络操作的observable。客户端代码可能经常订阅observable,这会导致高网络负载。

由于我们无法控制订户何时出现,因此必须在可观察方面进行。

1 个答案:

答案 0 :(得分:2)

当并发订阅者数量达到最大值时,您希望其他订阅者收到空流。

鉴于您要限制订阅的来源,请执行以下操作:

Observable<T> limited = source.compose(
        new TransformerLimitSubscribers<T>(
            new AtomicInteger(), maxSubscribers))
     .onErrorResumeNext(Observable.<T>empty());
...
limited.subscribe(s1);
...
limited.subscribe(s2); 

变换器由此类定义:

public final class TransformerLimitSubscribers<T> implements Transformer<T, T> {

    private final AtomicInteger subscriberCount;
    private final int maxSubscribers;

    public TransformerLimitSubscribers(AtomicInteger subscriberCount, int maxSubscribers) {
        this.subscriberCount = subscriberCount;
        this.maxSubscribers = maxSubscribers;
    }

    @Override
    public Observable<T> call(Observable<T> o) {
        return o.doOnSubscribe(onSubscribe()).doOnUnsubscribe(onUnsubscribe());
    }

    private Action0 onSubscribe() {
        return new Action0() {

            @Override
            public void call() {
                if (subscriberCount.incrementAndGet() > maxSubscribers)
                    throw new TooManySubscribersException();
            }
        };
    }

    private Action0 onUnsubscribe() {
        return new Action0() {

            @Override
            public void call() {
                subscriberCount.decrementAndGet();
            }
        };
    }

    public static class TooManySubscribersException extends RuntimeException {
    }

}