Skip to content

Instantly share code, notes, and snippets.

@shikajiro
Last active December 27, 2017 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shikajiro/13d8104683e8db2f7a4c6178e8775e73 to your computer and use it in GitHub Desktop.
Save shikajiro/13d8104683e8db2f7a4c6178e8775e73 to your computer and use it in GitHub Desktop.
Implementation to make it easier to manage Composition of RxJava 2 using LifecycleObserver of Android Architecture Component and Delegate of Kotlin
/* 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()
}
}
@shikajiro
Copy link
Author

shikajiro commented Dec 27, 2017

/* 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
   ...
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment