Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android timer with RxJava

I want to implement simple timer, which will counting values from 1 to 30 every second. When it reach 30 i want it to stop. Now i have something like this, but i don't know how to stop it after 30 seconds.

Here's the code:

Observable<Long> observable = Observable.interval(1, TimeUnit.SECONDS);

    observable.subscribe(
            new Action1<Long>() {
                @Override
                public void call(Long aLong) {
                    Log.d("Observable timer: ", aLong.toString());
                }
            },
            new Action1<Throwable>() {
                @Override
                public void call(Throwable error) {
                    System.out.println("Error encountered: " + error.getMessage());
                }
            },
            new Action0() {
                @Override
                public void call() {
                    System.out.println("Sequence complete");
                }
            }
    );
like image 588
wegtis Avatar asked Nov 28 '22 08:11

wegtis


1 Answers

Do you want to count once?

Observable.interval(1, TimeUnit.SECONDS)
.take(30) // up to 30 items
.map(v -> v + 1) // shift it to 1 .. 30
.subscribe(System.out::println);

Thread.sleep(35000);

Count repeatedly from 1 to 30?

Observable.interval(1, TimeUnit.SECONDS)
.map(v -> (v % 30) + 1) // shift it to 1 .. 30
.subscribe(System.out::println);

Thread.sleep(91000);
like image 111
akarnokd Avatar answered Dec 04 '22 13:12

akarnokd