Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Wait until a fragment is created and execute a lambda with the fragment as an argument.
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent
inline fun <reified T : Fragment>Fragment.waitUntilCreated(crossinline callback: (T) -> Unit) {
val activationObject: LifecycleOwner = this
object : LifecycleObserver {
init {
fun onCreate() {
check(activationObject is T) {
"The activation object and the generic type differs."
callback(activationObject as T)

This comment has been minimized.

Copy link
Owner Author

@GiorgioNatili GiorgioNatili commented Apr 21, 2018

Sample usage

fragment.waitUntilCreated<DecksFragment> { 
    println("Do whatever you want with ${it}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.