Is there RxJava equivalent of Handler.postDelayed(Runnable r, long delayMillis) Is there RxJava equivalent of Handler.postDelayed(Runnable r, long delayMillis) multithreading multithreading

Is there RxJava equivalent of Handler.postDelayed(Runnable r, long delayMillis)


You can achieve this with defer, delay and doOnNext.

Observable.defer(() -> Observable.just(null)            .delay(3, TimeUnit.SECONDS))            .doOnNext(ignore -> LogUtils.d("You action goes here"))            .subscribe();

In RxJava 2 you can use the following:

Completable.complete()     .delay(3, TimeUnit.SECONDS)     .doOnComplete(() -> System.out.println("Time to complete " + (System.currentTimeMillis() - start)))     .subscribe();

Test code for Paul's version:

    @Testpublic void testTimeToDoOnSubscribeExecution() {    final long startTime = System.currentTimeMillis();    System.out.println("Starting at: " + startTime);    Subscription subscription = Observable.empty()            .doOnSubscribe(() -> System.out.println("Time to invoke onSubscribe: " + (System.currentTimeMillis() - startTime)))            .delay(1000, TimeUnit.MILLISECONDS)            .subscribe();    new TestSubscriber((rx.Observer) subscription).awaitTerminalEvent(2, TimeUnit.SECONDS);}

Output:

Starting at: 1467280697232Time to invoke onSubscribe: 122


Use simply

subscription = Observable.timer(1000, TimeUnit.MILLISECONDS)            .subscribeOn(Schedulers.io())            .observeOn(AndroidSchedulers.mainThread())            .subscribe(aLong -> whatToDo());private void whatToDo() {   System.out.println("Called after 1 second");}


If you dont want to emit anything in your pipeline I dont see the point to use a pipeline, just to use the delay?.

Anyway, what you want to achieve does not has sense, you cannot create an Observable that does not emit anything.

But if you want to use it anyway you can always use an operator like doOnSubscribe

     @Test   public void observableDoOnSubscribe() {    Observable.empty()              .delay(50, TimeUnit.MILLISECONDS              .doOnSubscribe(() -> getView().setAttachments(attachments))              .subscribe();}

To test that delay works

        boolean onSubscribe = false;@Testpublic void observableDoOnSubscribe() {    Subscription subscription = Observable.just(System.currentTimeMillis())              .doOnSubscribe(() -> onSubscribe = true)              .delay(1000, TimeUnit.MILLISECONDS)              .filter(s -> onSubscribe)              .subscribe(t-> System.out.println("Pipeline spend time:" + (System.currentTimeMillis()-t)));    new TestSubscriber((Observer) subscription)            .awaitTerminalEvent(2, TimeUnit.SECONDS);}

More reactive examples here https://github.com/politrons/reactive