Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created December 14, 2018 19:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save afollestad/4a8b08b90a30b3445222c7fce38f4902 to your computer and use it in GitHub Desktop.
Save afollestad/4a8b08b90a30b3445222c7fce38f4902 to your computer and use it in GitHub Desktop.
Make an Observable Lifecycle aware - disposing itself when the lifecycle stops
/** @author Aidan Follestad (afollestad) */
class LifecycleAwareDisposable(
private val disposable: Disposable
) : LifecycleObserver {
@OnLifecycleEvent(ON_DESTROY)
fun dispose() = disposable.dispose()
}
/** @author Aidan Follestad (afollestad) */
fun LifecycleOwner.ownRx(disposable: Disposable) {
this.lifecycle.addObserver(LifecycleAwareDisposable(disposable))
}
/** @author Aidan Follestad (afollestad) */
fun Disposable.attachLifecycle(lifecycleOwner: LifecycleOwner) {
lifecycleOwner.ownRx(this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment