Kotlin extensions to commit Fragments safely 😎
Marc Garcia
2562

if (!supportFragmentManager.isStateSaved) {
ft.commit()
} else if (allowStateLoss) {
ft.commitAllowingStateLoss()
}

I’m afraid the logic of your code is incorrect.

isStateSaved() simply allows to know in advance if a state loss will occur if you try to commit, it doesn’t prevent state losses.

  • If you call your replaceFragmentSafely() with allowStateLoss set to true, then you can simply call commitAllowingStateLoss() and you don’t need to do any extra check. This method will never throw an exception and will perform the transaction if safe, else it will not perform the transaction and you’ll have a state loss.
  • If you call your replaceFragmentSafely() with allowStateLoss set to false, then your code does exactly what commitAllowingStateLoss() already does internally. Which means that if the state was already saved, none of the 2 commit() methods will end up being called, the transaction will not be performed and you’ll also have a state loss. Thus the allowStateLoss argument is not respected: if set to false and you can’t commit safely, you should return an error. Which is what commit() does.

Bottom line: your code does the same thing as simply calling commitAllowingStateLoss() and the allowStateLoss argument is not respected and should be removed.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.