I'm trying to replace my Handler method with RxJava.
My requirement:
I want to call the method getTransactionDetails() only after 5 seconds.
This my working code using Handler:
new Handler().postDelayed(new Runnable() { @Override public void run() { getTransactionDetails(); } }, 5000);
Rx java code - it's not working:
Observable.empty().delay(5000, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(o -> getTransactionDetails()) .subscribe();
Usually, asynchronous code is non-blocking: You call a method that returns immediately, allowing your code to continue its execution. Once the result of your call is available, it is returned via a callback. RxJava is asynchronous, too.
Single and Completable are new types introduced exclusively at RxJava that represent reduced types of Observable , that have more concise API. Single represent Observable that emit single value or error. Completable represent Observable that emits no value, but only terminal events, either onError or onCompleted.
RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself. RxJava's former fans and advocates moved on to new shiny things, so there is no one left to say a proper eulogy over this, once very popular, framework.
Flowable: emit a stream of elements (endlessly, with backpressure) Single: emits exactly one element. Maybe: emits zero or one elements. Completable: emits a “complete” event, without emitting any data type, just a success/failure.
This is how I would do it:
Completable.timer(5, TimeUnit.SECONDS, AndroidSchedulers.mainThread()) .subscribe(this::getTransactionDetails);
A Completable represents a deferred computation with no value but an indication for completion or exception. The static method call timer()
returns a Completable
that signals completion after the specified time period has elapsed, and the subscribe()
call will mean that the method getTransactionDetails()
will be called on the current object when the timer fires. By supplying a Scheduler
as the last argument to Completable.timer()
you control which thread is used to execute getTransactionDetails()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With