Skip to content

Instantly share code, notes, and snippets.

@ZeroBrain

ZeroBrain/LifecycleUtil.kt

Last active Jul 16, 2017
Embed
What would you like to do?
Rxjava with Lifecycle-awareness for Lifecycle of Android Architecture Component
object FlowableForLifecycle {
fun <T> flowableForLifecycle(lifecycleOwner: LifecycleOwner, data: Flowable<T>, atLeast:Lifecycle.State = Lifecycle.State.RESUMED): Flowable<T> {
return Flowable.combineLatest(Flowable.create<Lifecycle.State>({ e ->
val observer: GenericLifecycleObserver = object : GenericLifecycleObserver {
override fun getReceiver(): Any = lifecycleOwner
override fun onStateChanged(owner: LifecycleOwner, event: Lifecycle.Event) {
e.takeIf { !e.isCancelled }?.onNext(owner.lifecycle.currentState)
if (event == Lifecycle.Event.ON_DESTROY) {
lifecycleOwner.lifecycle.removeObserver(this)
}
}
}
lifecycleOwner.lifecycle.addObserver(observer)
e.setCancellable { lifecycleOwner.lifecycle.removeObserver(observer) }
}, BackpressureStrategy.LATEST),
data,
BiFunction<Lifecycle.State, T, T> { _, t2 -> t2 })
.filter { lifecycleOwner.lifecycle.currentState.isAtLeast(atLeast) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.