R. Zagórski R. Zagórski - 5 months ago 69
Java Question

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

I am trying to invoke a method that returns void (Java primitive type). I would like to delay the invoking of a it by a predefined amount of milliseconds. I know this can be simply done using a

Handler
by I prefer not to use it.

I tried to do:

Observable.just(getView().setAttachments(attachments)).delay(50, TimeUnit.MILLISECONDS);


However, there is a compilation error, that:

Observable.just(java.lang.Void) cannot be applied to (void)


Is there another way? The reason I would like not to use a
Handler
is that the code is defined in Presenter (MVP pattern) and I would not like to use Android specific code in Java only class.
I would prefer it to be a cold Observable, as I would not have to subscribe to it, just invoke the method only once.

Answer

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;

@Test
public 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