Status Update
Comments
[Deleted User] <[Deleted User]> #2
We ran into this issue when reusing DialogFragment
s. Given a DialogFragment
which accesses a ViewModel
in onCreate
, after it's dismissed, it receives Lifecycle.Event.ON_DESTROY
. If the DialogFragment
is shown again, it will throw in onCreate
when trying to access the ViewModel
again.
Granted, it's fairly easy to avoid by either creating a new DialogFragment
for every show or using lazy
to fetch the ViewModel
a single time. However, this is a fairly easy trap to fall into.
il...@google.com <il...@google.com>
sa...@google.com <sa...@google.com>
il...@google.com <il...@google.com>
il...@google.com <il...@google.com> #3
As of DESTROYED
, so there's no longer any way to re-register a second time on a given LifecycleOwner
/ SavedStateRegistryOwner
(noting that the DESTROYED
state is a terminal state that will never go back through ON_CREATE
ever again - it is always a brand new Lifecycle
and SavedStateRegistry
even if you are improperly reusing a destroyed fragment).
Description
Component used: SavedStateHandleController Version used: 2.3.0-beta01 Devices/Android versions reproduced on: Pixel 3 XL / Android 11
The behavior in the lifecycle lib is: If you attempt to read a ViewModel from viewmodel store and if a SavedStateProvider is previously registered by the same ViewModel key, it throws an IllegalArgumentException "SavedStateProvider with the given key is already registered".
For example, if my viewmodel is scoped to an activity and if I try to access the viewmodel from viewmodel store after the activity has received the onDestroy lifecycle event, I get this IllegalArgumentException.
Looking at the code in lifecycle lib, it seems that it does not unregister itself when detaching upon ON_DESTROY lifecycle event.
When it detaches:https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:lifecycle/lifecycle-viewmodel-savedstate/src/main/java/androidx/lifecycle/SavedStateHandleController.java;l=55?q=savedstatehandlecontroller
When it tries to reattach:https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:lifecycle/lifecycle-viewmodel-savedstate/src/main/java/androidx/lifecycle/SavedStateHandleController.java;l=101?q=savedstatehandlecontroller
Is it possible to implement a more robust solution/handling around this IllegalArgumentException so that, as user of the lib, I don't have to be so cautious?