Skip to content

Instantly share code, notes, and snippets.

@edenman
Created November 15, 2017 22:19
Show Gist options
  • Save edenman/ad28420613d3068d34d62d8eb8856c9e to your computer and use it in GitHub Desktop.
Save edenman/ad28420613d3068d34d62d8eb8856c9e to your computer and use it in GitHub Desktop.
View.observeVisibility()
fun View.observeVisibility(): Observable<Int> =
Observable.create(ViewVisibilityChangeOnSubscribe(this), BackpressureMode.LATEST)
private class ViewVisibilityChangeOnSubscribe(private val view: View) : Action1<Emitter<Int>> {
override fun call(emitter: Emitter<Int>) {
val listener = OnGlobalLayoutListener {
if (view.viewTreeObserver.isAlive) {
emitter.onNext(view.visibility)
}
}
emitter.setCancellation {
if (view.viewTreeObserver.isAlive) {
view.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
}
val originalVisibility = view.visibility
emitter.onNext(originalVisibility)
view.viewTreeObserver.addOnGlobalLayoutListener(listener)
}
}
@edenman
Copy link
Author

edenman commented Nov 20, 2017

In case anybody stumbles across this: I've stopped using it, for a few reasons:

  • it has a memory leak if a parent view A observes the visibility of a child B and then unsubscribes in A's onDetachedFromWindow. Fixing this would require also hooking up an OnAttachStateChangeListener and removing both the OnAttachStateChangeListener and the OnGlobalLayoutListener if the view is detached.
  • it's super chatty, since it publishes an event on every layout pass. Could solve this with a distinctUntilChanged but it's still doing alot of work.
  • it fundamentally inverts the logic flow: it's generally a better idea to just refactor your other observables that control the visbility of the view such that the same observable can be used in place of observeVisibility

(big ups to Adam Powell from Google for helping me realize why the memory leak was happening, and suggesting the last two problems)

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