Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Timer using RxJava

Currently I'm using a CountDownTimer that count down from a number and onFinish run an action and reset the timer, starting the count down from another number.

For example inputs like this:

Remaining time = 13 | Interval = 30

Result in a output like this:

13 12 .. 3 2 1 0 30 29 .. 3 2 1 0 30 29 ...

I've tried to create a chain that generate the desired output using interval, delay and other operators but I'm yet to find a solution.

like image 801
Keivan Esbati Avatar asked Apr 17 '26 00:04

Keivan Esbati


1 Answers

One of possible solutions

fun countDown(startCounter: Long, nextCounter: Long): Observable<Long> {
    return Observable.intervalRange(startCounter, startCounter+2, 0, 1, TimeUnit.SECONDS)
            .map { 2*startCounter - it }
            .flatMap { if(it >= 0) Observable.just(it) else countDown( nextCounter, nextCounter) }

}

And then use it like

countDown(13, 30)
            .subscribeOn(Schedulers.computation())
            .subscribe({
                System.out.println(it.toString())
            }, {
                it.printStackTrace()
            })

The result should be as you expected.

like image 110
ConstOrVar Avatar answered Apr 19 '26 14:04

ConstOrVar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!