Skip to content

Instantly share code, notes, and snippets.

@tpakis
Last active January 1, 2021 21:25
Show Gist options
  • Save tpakis/9a8d5d0c6a4183ae197575c96f8aeb97 to your computer and use it in GitHub Desktop.
Save tpakis/9a8d5d0c6a4183ae197575c96f8aeb97 to your computer and use it in GitHub Desktop.
Auto clearing view reference for fragments
class BindViewDelegate<T>(
private val createView: () -> T,
private val getLifecycle: () -> Lifecycle
) : Lazy<T>, LifecycleObserver {
private var view: T? = null
private val lifecycle: Lifecycle?
get() = try {
getLifecycle()
} catch (e: IllegalStateException) {
Log.e("BindViewDelegate", e.message)
null
}
override val value: T
get() {
if (view == null) {
lifecycle?.removeObserver(this)
view = createView()
lifecycle?.addObserver(this)
}
@Suppress("UNCHECKED_CAST")
return view as T
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
reset()
}
private fun reset() {
lifecycle?.removeObserver(this)
view = null
}
override fun isInitialized(): Boolean = view != null
}
fun <T : View> Fragment.bindView(@IdRes resource: Int): Lazy<T> = BindViewDelegate(
createView = { requireView().findViewById<T>(resource) },
getLifecycle = { viewLifecycleOwner.lifecycle }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment