Status Update
Comments
il...@google.com <il...@google.com> #2
If you remove the call to recreate()
and update your MainActivity
to do something like:
class MainActivity : FragmentActivity() {
var beforeSuperOnDestroy: (() -> Unit)? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(FrameLayout(this))
}
override fun onDestroy() {
beforeSuperOnDestroy?.invoke()
super.onDestroy()
}
}
Thus unconditionally adding the Fragment right before super.onDestroy()
(which is 1) after the state would have been saved and 2) before the Fragments are destroyed and ViewModels are cleared), you'll see that the Fragment and its ViewModel is indeed corrected destroyed when your test does moveToState(Lifecycle.State.DESTROYED)
.
What is happening when you do call recreate()
is more clear if you update your tests with:
recreate()
onActivity {
// This assert fails when the fragment is added after the state is saved
assertThat("TestFragment doesn't exist in the FragmentManager",
it.supportFragmentManager.findFragmentByTag(tag) != null)
}
moveToState(Lifecycle.State.DESTROYED)
You'll note that when you add a Fragment after the state is saved, it isn't restored because it was never saved in the first place. This is why there are warnings on the AllowingStateLoss()
methods and why the isStateSaved()
This isn't a regression (you'd see the same behavior on any Fragment 1.2.X build), but I'll leave this is open to investigate whether we can detect that the fragment has been added after the state is saved so as to treat that first onDestroy()
as the final one, clearing the ViewModels associated with those fragments since the fragment isn't coming back.
Description
Version used: 1.3.0-beta01
I attached sample project with 2 robolectric tests:
- `Clear ViewModels for fragment added before state save` - passes
- `Clear ViewModels for fragment added after state save` - fails
Because ActivityScenario don't have methods to just trigger state save I have to use recreate() call for this behavior. Not clearing ViewModels could lead to memory leaks and I think FragmentStateManager should clear ViewModels for fragments added after state save.
BTW it would be great if you introduce some mechanism to determine if fragment is destroying temporary or forever (like something like Activity.isFinishing but for fragments).