Skip to content Skip to sidebar Skip to footer

Pause Between Call Onnext In Rxjava

How to make delay between onNext method calling? I have a code: Observable obs = Observable.range(1, 1000) .subscribeOn(Schedulers.io())

Solution 1:

Well you can use interval operator which will emit items after a specified interval of time and use take operator to use only required numbers of stream items

Observable.interval(100, TimeUnit.MILLISECONDS)
        .take(1000)
         .subscribe(newAction1<Long>() {
          @Overridepublicvoidcall(Long timerValue) {

        }
        });

Solution 2:

One way to do it is to use zip to combine your observable with an Interval observable to delay the output.

 Observable.zip(Observable.range(1, 5)
    .groupBy(n -> n % 5)
    .flatMap(g -> g.toList()),
Observable.interval(50, TimeUnit.MILLISECONDS),
(obs, timer) -> obs)
.doOnNext(item -> {
  System.out.println(System.currentTimeMillis() - timeNow);
  System.out.println(item);
  System.out.println(" ");
}).toList().toBlocking().first();

Solution 3:

If you want 1,2,3...1000 how about this:

subs = Observable.interval(0, 100, TimeUnit.MILLISECONDS, Schedulers.io())
        .take(1000)
        .map(counter -> counter++)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(newSubscriber<Long>() {
            @OverridepublicvoidonNext(Long number) {
                mCurrentNumber = number;
                mCounter.setText(String.valueOf(number));
            }

            @OverridepublicvoidonCompleted() {
                isRunning = false;
            }

            @OverridepublicvoidonError(Throwable e) {

            }
        });
  • .interval will run on IO
  • This will start immediately emitting items 0L, 1L, 2L......infinity.
  • The .take(1000) will take the first 1000 items and then stop (complete)
  • The .map(counter -> counter++) will transform the above to 1L, 2L,......infinity because you requested from 1 to 1000 in your example and not 0 to 1000.

If you want 100,200,300 then use .map(counter -> counter*100)

If you want to "sample" per 100ms the range, thus creating a bit random numbers then use:

Observable.range(1, 1000)
        .subscribeOn(Schedulers.io())
        .sample(100, TimeUnit.MILLISECONDS)
        ......
        //rest here

Post a Comment for "Pause Between Call Onnext In Rxjava"