简体   繁体   English

RxJava。 如何让 Observable 计时器在后台运行?

[英]RxJava. How do I make the Observable timer run in the background?

I need to make sure that after pressing one button, the other is not available for 15 minutes.我需要确保按下一个按钮后,另一个按钮在 15 分钟内不可用。 To do this, I use a method like this:为此,我使用这样的方法:

disposableTimer = Observable.timer(15,TimeUnit.MINUTES)
                            .subscribeOn(Schedulers.io())
                            .observeOn(Schedulers.io())
                            .subscribe(aLong -> {
                                  buttonSimpleAct.setEnabled(true);
                            });

This works well when the program is active, but I need this timer to work even when the program is closed.这在程序处于活动状态时效果很好,但即使程序关闭,我也需要这个计时器工作。 That is, if the first button was pressed, the application was closed and returned after 15 minutes, the second button should already be active.也就是说,如果按下第一个按钮,应用程序在 15 分钟后关闭并返回,则第二个按钮应该已经处于活动状态。

Are there any ways to make the Observable work in the background, or alternatives to this?有什么方法可以让 Observable 在后台工作,或者替代它吗?

What I'd do is save (in a persistent manner) the timestamp for when the button should be re-enabled and restart the timer with the remaining time when the app comes back.我要做的是(以持久的方式)保存按钮何时应该重新启用的时间戳,并在应用程序返回时用剩余时间重新启动计时器。

// when the first button is clicked:
long reenableAfter = System.currentTimeMillis() + 15 * 60 * 1000L;
save(reenableAfter);

disposableTimer = Observable.timer(15 ,TimeUnit.MINUTES, AndroidSchedulers.mainThread())
    .subscribe(aLong -> buttonSimpleAct.setEnabled(true));
// when the app starts
long reenableAfter = load();

disposableTimer = Observable.timer(reenableAfter - System.currentTimeMillis(),
          TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
    .subscribe(aLong -> buttonSimpleAct.setEnabled(true));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM