The other answers are a bit outdated and one didn't work for me (wrote there my comments about it), so here's what I think is updated and working:
On the onCreateDialog
callback, have your logic of when it succeeds. If failed, return some default dialog (won't be used anyway) while adding to the lifecycle's onStart callback to dismiss the DialogFragment (use dismiss
or dismissAllowingStateLoss
):
fun Lifecycle.runOnStarted(runnable: () -> Unit) {
addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
runnable.invoke()
}
})
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
//create the builder of the dialog, and then check if need to dismiss
if (needToDismiss) {
lifecycle.runOnStarted{
dismissAllowingStateLoss()
}
return builder.create()
}
Alternative, using kotlin coroutines and without using the helper function I've made:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
//create the builder of the dialog, and then check if need to dismiss
if (needToDismiss) {
lifecycleScope.launch {
whenStarted {
dismissAllowingStateLoss()
}
}
return builder.create()
}
Or you can use this helper function that uses kotlin coroutines to make it a bit shorter:
fun LifecycleOwner.runOnStarted(runnable: () -> Unit) {
lifecycleScope.launch {
whenStarted{
runnable.invoke()
}
}
}
The usage would be as short as before:
runOnStarted{
dismissAllowingStateLoss()
}
Note that I use onStart callback instead of onCreate. The reason is that for some cases, onStart works, while onCreate won't.