18
8

More than 5 years have passed since last update.

RxJava2 の disposable の管理をいともたやすく行うための LifecycleObserver を実装した Delegate 用クラス

Last updated at Posted at 2017-12-27

RxJava での subscribe の管理ってまじ大変ですよね。CompositeDisposable を使うと思うのですが、Activityのソースがその処理ばかりになって読みづらくなりますよね。

そこで、KotlinでAndroidのRxJavaをちょっと便利に - Qiita を参考に AutoUnSubscribable を使うと思うのですが、 onResume onPause の呼び出しを忘れがちだったりしますよね。よね。

んで最近 Android Architecture Component が出てきて LifecycleObserver を使えばライフサイクルを簡単に管理できるようになりました。

これらを組み合わせて、RxJava2 の disposable の管理をいともたやすく行うための LifecycleObserver を実装した Delegate 用クラスを作りました。

RxJava2慣れてなくて自信が無いのでだれかなじってください。
修正すると思うので gist の方を信じてください。

RxJava2LifecycleObserver.kt

/* Interface is necessary for Delegate */
interface RxJava2LifecycleDelegate {
  fun Disposable.autoDispose(): Disposable
  fun Lifecycle.setupRxJava2Observer(func: () -> Unit)
}

/* Class for Delegate implementing LifecycleObserver */
class RxJava2LifecycleDelegateImpl : RxJava2LifecycleDelegate {
  private var composite = CompositeDisposable()

  /**
   * Extension function for registering LifecycleObserver and subscribe method
   * @func: This lambda calls subscription processing
   */
  override fun Lifecycle.setupRxJava2Observer(func: () -> Unit) {
    addObserver(RxJava2LifecycleObserver(composite, func))
  }

  private fun check() {
    if (composite.isDisposed) {
      composite = CompositeDisposable()
    }
  }

  /* Extension function for composite management of Disposable  */
  override fun Disposable.autoDispose(): Disposable {
    check()
    composite.add(this)
    return this
  }
}

class RxJava2LifecycleObserver(private val composite: CompositeDisposable,
                               private val subscribeCallback: () -> Unit)
  : LifecycleObserver {

  /* It is automatically called at onResume timing and sets up subscription processing. */
  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  fun subscribe() {
    subscribeCallback()
  }

  /* It is automatically called at the timing of onPause and releases subscription processing. */
  @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
  fun dispose() {
    composite.dispose()
  }
}

上記のクラスを使った実装例

/* Example Implementation */
class ExampleActivity : AppCompatActivity(), RxJava2LifecycleDelegate by RxJava2LifecycleDelegateImpl() {

  override fun onCreate(savedInstanceState: Bundle?) {
    ...
    // Register the Observer to subscribe onResume and dispose with onPause
    lifecycle. setupRxJava2Observer(this::subscribes)
  }

  /* subscribe method */
  private fun subscribes() {
    //subscribe example
    vm.progress.subscribe {
      if (it) showProgress() else dismissProgress()
    }.autoDispose() //Monitor disposable
   ...
  }
}
18
8
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
18
8