Skip to content

Instantly share code, notes, and snippets.

@tpakis
Created January 1, 2021 21:38
Show Gist options
  • Save tpakis/bfed90ab7779fc4b9cfac2ec28c652e1 to your computer and use it in GitHub Desktop.
Save tpakis/bfed90ab7779fc4b9cfac2ec28c652e1 to your computer and use it in GitHub Desktop.
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 }
)
fun <T : View> Activity.bindView(@IdRes res: Int): Lazy<T> {
@Suppress("UNCHECKED_CAST")
return lazy(LazyThreadSafetyMode.NONE) { findViewById<T>(res) }
}
fun <T : View> View.bindView(@IdRes res: Int): Lazy<T> {
@Suppress("UNCHECKED_CAST")
return lazy(LazyThreadSafetyMode.NONE) { findViewById<T>(res) }
}
fun <T : View> RecyclerView.ViewHolder.bindView(@IdRes res: Int): Lazy<T> {
@Suppress("UNCHECKED_CAST")
return lazy(LazyThreadSafetyMode.NONE) { itemView.findViewById<T>(res) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment