简体   繁体   中英

RxJava Observable minimum execution time

I have an Observable (which obtains data from network). The problem is that observable can be fast or slow depending on network conditions.

I show progress widget, when observable is executing, and hide it when observable completes. When the network is fast - progress flikers (appears and disappears). I want to set minimum execution time of observable to 1 second. How can I do that?

"Delay" operator is not an option because it will delay even for slow network.

You can use Observable.zip() for that. Given

Observable<Response> network = ...

One can do

Observable<Integer> readyNotification = Observable.just(42).delay(1, TimeUnit.SECONDS);
Observable delayedNetwork = network.zipWith(readyNotification, 
                                                (response, notUsed) -> response);

Use Observable.concatEager()

It allows you to force one stream to complete after another (concat operator), but also kick off the network request immediately without having to wait for the first argument observable to complete (concatEager):

Observable<Response> responseObservable = ...;

Observable<Response> responseWithMinDelay = Observable.concatEager(
                    Observable.timer(1, TimeUnit.SECONDS).ignoreElements(),
                    responseObservable
).cast(Response.class);

It looked like Observable.zip would be a reasonable approach, and it seemed to work well until there was an error emitted; then it didn't wait for the expected time.

This seemed to work well for me:

Observable.mergeDelayError(
        useCase.execute(), // can return Unit or throw error
        Observable.timer(1, TimeUnit.SECONDS)
)
.reduce { _, _ -> Unit }
.doOnError { /* will wait at least 1 second */ }
.subscribe { /* will wait at least 1 second */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM