Search code examples
javaandroidtimerbackgroundrx-java

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. 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.

Are there any ways to make the Observable work in the background, or alternatives to this?


Solution

  • 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));