带有RxJava的Android计时器

weg*_*tis 4 android observable rx-java

我想实现简单的计时器,它将每秒计数1到30的值.当它达到30时,我希望它停止.现在我有类似的东西,但我不知道如何在30秒后停止它.

这是代码:

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");
                }
            }
    );
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

aka*_*okd 13

你想算一次吗?

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);
Run Code Online (Sandbox Code Playgroud)

重复计数从1到30?

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

Thread.sleep(91000);
Run Code Online (Sandbox Code Playgroud)

  • @wegtis `.observeOn(AndroidSchedulers.mainThread()).subscribe(result -&gt; textView.setText(result));` (3认同)

Ser*_*hev 9

您可以像这样实现它:

public static final int TIMER_VALUE = 30;

....

Observable.interval(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(new Consumer<Long>() {
                public void accept(Long x) throws Exception {
                    // update your view here
                    myTextView.setText(String.valueOf(x));
                }
            })
            .takeUntil(aLong -> aLong == TIMER_VALUE)
            .doOnComplete(() ->
                    // do whatever you need on complete
            ).subscribe()
Run Code Online (Sandbox Code Playgroud)

  • 不需要 subscribeOn 运算符,因为默认情况下间隔在 Schedulers.computation 线程上运行... (2认同)