Created
April 21, 2018 16:28
-
-
Save GiorgioNatili/b647bccea930d27dbf93e6c01c176119 to your computer and use it in GitHub Desktop.
Wait until a fragment is created and execute a lambda with the fragment as an argument.
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
import android.arch.lifecycle.Lifecycle | |
import android.arch.lifecycle.LifecycleObserver | |
import android.arch.lifecycle.LifecycleOwner | |
import android.arch.lifecycle.OnLifecycleEvent | |
import android.support.v4.app.Fragment | |
inline fun <reified T : Fragment>Fragment.waitUntilCreated(crossinline callback: (T) -> Unit) { | |
val activationObject: LifecycleOwner = this | |
object : LifecycleObserver { | |
init { | |
activationObject.lifecycle.addObserver(this) | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) | |
fun onCreate() { | |
check(activationObject is T) { | |
"The activation object and the generic type differs." | |
} | |
callback(activationObject as T) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage