Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava/Android monitor progress of multiple subscribers fired at different times

I am looking for a way, hopefully using RxJava for consistency, to monitor the progress of multiple subscribers that may be fired at different times. I am aware of how to merge or flatMap subscribers together when they are all fired from one method but I am unaware of a way to do it when they are fired at different times from different methods.

For example, if I have 2 long running tasks attached to button presses. I push button 1 and fire off the observable/subscriber, half way through running I push button 2 to fire off the second observable/subscriber.

I want to enable a button when no tasks are running and disable it when one or more tasks are running.

Is this possible? I am trying to avoid setting instance variable flags as well.

like image 248
Ben Trengrove Avatar asked Nov 22 '25 07:11

Ben Trengrove


1 Answers

I would use a separate BehaviorSubject and scan to monitor execution status. This is quite similar to an instance variable, but probably it can inspire you to a better solution. Something like this:

private final BehaviorSubject<Integer> mProgressSubject = BehaviorSubject.create(0);

public  Observable<String> firstLongRunningOperations() {
    return Observable.just("First")
            .doOnSubscribe(() -> mProgressSubject.onNext(1))
            .finallyDo(() -> mProgressSubject.onNext(-1)));
}

public  Observable<String> secondLongRunningOperations() {
    return Observable.just("Second")
            .doOnSubscribe(() -> mProgressSubject.onNext(1))
            .finallyDo(() -> mProgressSubject.onNext(-1));
}

public Observable<Boolean> isOperationInProgress() {
    return mProgressSubject.asObservable()
            .scan((sum, item) -> sum + item)
            .map(sum -> sum > 0);
}

Usage will be like this:

isOperationInProgress()
        .subscribe(inProgress -> {
            if (inProgress) {
                //disable controls
            } else {
                //enable controls
            }
        });

With this approach you can have any number of long running operation and you do not have to fire them all. Just don't forget to call doOnSubscribe and finallyDo.

PS. Sorry, I didn't test it, but it should work.

like image 94
MyDogTom Avatar answered Nov 24 '25 23:11

MyDogTom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!