Skip to content

Instantly share code, notes, and snippets.

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 TommyPersson/0a2ba70b252a727e8e61954073c51066 to your computer and use it in GitHub Desktop.
Save TommyPersson/0a2ba70b252a727e8e61954073c51066 to your computer and use it in GitHub Desktop.
fun AppCompatActivity.subscribeToBroadcastsOnLifecycle(action: String, fn: (Intent) -> Unit) {
observeBroadcasts(action).subscribeOnLifecycle(lifecycle, fn)
}
fun <T> Observable<T>.subscribeOnLifecycle(lifecycle: Lifecycle, fn: (T) -> Unit) {
val lifecycleObserver: LifecycleObserver = object : LifecycleObserver {
private var subscription: Disposable? = null
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
subscription = subscribe(fn)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
subscription?.dispose()
}
}
lifecycle.addObserver(lifecycleObserver)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment