I'm using databinding, the Jetpack Navigation Component (in which one activity hosts several fragments) and a shared ViewModel with activityViewModels()
in the fragments. The Room database is initialized (and some resource expensive queries) when a ViewModel function is called from the StartFragment (hosted by the MainActivity). The host activity is created twice (and destroyed once), causing the fragment to do the same and duplicate Room queries.
ViewModel varialble in the Fragment:
private val viewModel: WorkoutListViewModel by activityViewModels()
ViewModel function:
if (applicationStarted) {
roomDb = WorkoutsRoomDatabase.getInstance(application)
repository = WorkoutsRepository(roomDb)
collectAllWorkouts() // Expensive database query
insertWorkoutGroup(WorkoutGroup(FIRST_TAB_TITLE), null)
}
I know the activity, fragment creation and Room queries happen twice because I used logs to test it.
I suspect the cause is related to databinding, the navigation component, or the way the shared ViewModel with activityViewModels()
.
Even though there's better ways to initialize the database and start queries, I appreciate an input on this too but my question is specifically about the host activity being created twice.
edit: The activity it created -> destroyed -> created
The bundle is null at first and the second time it is:
Bundle[{android:viewHierarchyState=Bundle[{android:views={16908290=android.view.AbsSavedState$1@cd936b5, 2131230775=android.view.AbsSavedState$1@cd936b5, 2131230790=android.view.AbsSavedState$1@cd936b5, 2131231216=android.view.AbsSavedState$1@cd936b5}}], androidx.lifecycle.BundlableSavedStateRegistry.key=Bundle[{android:support:lifecycle=Bundle[{}], androidx.lifecycle.internal.SavedStateHandlesProvider=Bundle[{}]}], android:lastAutofillId=1073741824, android:fragments=android.app.FragmentManagerState@c25a14a}]