Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created December 14, 2018 18:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save afollestad/42d41598a2df05694023a6d1f4fd563c to your computer and use it in GitHub Desktop.
Save afollestad/42d41598a2df05694023a6d1f4fd563c to your computer and use it in GitHub Desktop.
Create a lifecycle owner for a view without any boiler plate
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item format="integer" name="view_lifecycle_registry" type="id"/>
</resources>
import android.view.View
import android.view.View.OnAttachStateChangeListener
import androidx.lifecycle.LifecycleOwner
/** @author Aidan Follestad (@afollestad) */
class ViewLifecycleOwner(view: View) : LifecycleOwner, OnAttachStateChangeListener {
private val lifecycle = SimpleLifecycle(this)
init {
view.addOnAttachStateChangeListener(this)
}
override fun getLifecycle() = lifecycle
override fun onViewAttachedToWindow(v: View?) = lifecycle.onCreate()
override fun onViewDetachedFromWindow(v: View) = lifecycle.onDestroy()
}
fun View.lifecycleOwner(): LifecycleOwner {
val tagOwner = getTag(R.id.view_lifecycle_registry) as? ViewLifecycleOwner
return if (tagOwner != null) {
tagOwner
} else {
val newOwner = ViewLifecycleOwner(this)
setTag(R.id.view_lifecycle_registry, newOwner)
newOwner
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment