Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method after a delay in android using rxjava?

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(); 
like image 661
Vibindas M Avatar asked Feb 08 '17 19:02

Vibindas M


People also ask

Is RxJava asynchronous?

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.

What is Completable RxJava?

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.

Is RxJava deprecated?

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.

What is flowable in RxJava Android?

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.


1 Answers

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().

like image 159
Clyde Avatar answered Sep 21 '22 16:09

Clyde