Last active
January 1, 2021 21:25
-
-
Save tpakis/9a8d5d0c6a4183ae197575c96f8aeb97 to your computer and use it in GitHub Desktop.
Auto clearing view reference for fragments
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
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