apps-android-wikipedia icon indicating copy to clipboard operation
apps-android-wikipedia copied to clipboard

Use SavedStateHandle in view models

Open Isira-Seneviratne opened this issue 1 year ago • 2 comments

Pass SavedStateHandle instead of Bundle to the view models. Values provided via an Intent's extras or a fragment's arguments are automatically passed to the state handle in the default view model factory implementation, which eliminates the need to implement a view model factory separately.

Isira-Seneviratne avatar Aug 19 '24 09:08 Isira-Seneviratne

Thanks -- this looks like it will be a worthwhile change. However, a change of this size requires a much better description. The word "simplify" is not meaningful enough. There is a considerable reduction in code, but why is there a reduction in code?

I updated the description to be more informative, hope that's better.

Is it because SavedStateHandle automatically provides access to the Activity's intent extras and/or the Fragment's arguments? If so, this should be very clearly specified in your description.

That's exactly what it does. The default view model factory automatically forwards data passed via the extras or arguments:

https://github.com/androidx/androidx/blob/androidx-main/activity/activity/src/main/java/androidx/activity/ComponentActivity.kt#L547 https://github.com/androidx/androidx/blob/976ab1f419ea26d4f7481267ffba338fb9b256ff/fragment/fragment/src/main/java/androidx/fragment/app/Fragment.java#L471

Isira-Seneviratne avatar Aug 19 '24 14:08 Isira-Seneviratne

This PR gets bigger and bigger. Should we separate it to multiple smaller PRs?

trietbui85 avatar Sep 29 '24 15:09 trietbui85