0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RxJavaのintervalでonPauseで停止、onResumeで再開させる

Posted at

やりたいこと

Observable.intervalを使って5秒おきにViewを操作させるアプリがあったとする。
アプリがバックグラウンドになればView操作を停止、フォアグラウンドならView操作を再開させたい。
これをRxJavaで実装してみた。

コード

private AtomicBoolean resumed = new AtomicBoolean();
private AtomicBoolean stopped = new AtomicBoolean();

private void start() {

    Observable.interval(5, TimeUnit.SECONDS)
      .observeOn(AndroidSchedulers.mainThread())
      .takeWhile(new Predicate<Long>() {
          @Override
          public boolean test(Long aLong) throws Exception {
              return !stopped.get();
          }
      })
      .filter(new Predicate<Long>() {
          @Override
          public boolean test(Long aLong) throws Exception {
              return resumed.get();
          }
      })
      .subscribeWith(new DisposableObserver<Long>() {

          @Override
          public void onNext(Long aLong) {
              logger.d("onNext " + aLong);
              // ここに動作させたい処理
          }

          @Override
          public void onError(Throwable e) {
              logger.e(e.getMessage());
          }

          @Override
          public void onComplete() {
              logger.d("onComplete");
          }
    })
}

@Override
public void onResume() {
    super.onResume();
    resumed.set(true);
    stopped.set(false);
    start();
}

@Override
public void onPause() {
    super.onPause();
    resumed.set(false);
    stopped.set(true);
}

感想

希望する動作をしてくれてはいるが、本当はKotlin+Coroutineで実装したかった。
今回はJavaという制約があったので仕方ない。

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?