Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava timer that repeats forever, and can be restarted and stopped at anytime

In android i use Timer to execute task that repeats every 5 seconds and starts after 1 second in this way:

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Here is the repeated task
        }
    }, /*Start after*/1000, /*Repeats every*/5000);

    // here i stop the timer
    timer.cancel();

this timer will repeat Until i call timer.cancel()

I am learning RxJava with RxAndroid extension

So i found this code on internet, i tried it and it doesnt repeat:

Observable.timer(3000, TimeUnit.MILLISECONDS)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<Long>() {
        @Override
        public void call(Long aLong) {
             // here is the task that should repeat
        }
    });

so what is the alternative for the android Timer in RxJava.

like image 829
MBH Avatar asked Jul 27 '16 06:07

MBH


4 Answers

timer operator emits an item after a specified delay then completes. I think you looking for the interval operator.

Subscription subscription = Observable.interval(1000, 5000, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Long>() {
                public void call(Long aLong) {
                    // here is the task that should repeat
                }
            });

if you want to stop it you just call unsubscribe on the subscription:

subscription.unsubscribe()
like image 102
csabapap Avatar answered Oct 17 '22 16:10

csabapap


Call Observable.repeat() method to repeat

Disposable disposable = Observable.timer(3000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.newThread())
.repeat()
.observeOn(AndroidSchedulers.mainThread())
.subscribe();

If you want to stop it call disposable.dispose()

like image 36
Anshuman Avatar answered Oct 17 '22 16:10

Anshuman


KOTLIN way

Observable.timer(5000, TimeUnit.MILLISECONDS)
            .repeat() //to perform your task every 5 seconds
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                Log.d("ComingHere", "Inside_Timer")
            }
like image 3
Sachin Avatar answered Oct 17 '22 16:10

Sachin


This is the right and secure way %100 working :

     //timer variable is in seconds unit
    int timer = 5;
    Disposable disposable = Observable.interval(timer, TimeUnit.SECONDS)
            .map((tick) -> {
                handler.post(() -> {
                    //Enter your CODE here !!!
                });
                return true;
            }).subscribe();

And for stoping it :

if (disposable != null) {
        disposable.dispose();
    }
like image 1
ParSa Avatar answered Oct 17 '22 17:10

ParSa