Created
November 15, 2017 22:19
-
-
Save edenman/ad28420613d3068d34d62d8eb8856c9e to your computer and use it in GitHub Desktop.
View.observeVisibility()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case anybody stumbles across this: I've stopped using it, for a few reasons:
onDetachedFromWindow
. Fixing this would require also hooking up anOnAttachStateChangeListener
and removing both theOnAttachStateChangeListener
and theOnGlobalLayoutListener
if the view is detached.distinctUntilChanged
but it's still doing alot of work.observeVisibility
(big ups to Adam Powell from Google for helping me realize why the memory leak was happening, and suggesting the last two problems)