Hi everyone, I just hit a roadblock using SafeArgs...
# android
t
Hi everyone, I just hit a roadblock using SafeArgs + Hilt + LiveData + ViewModel... my use case is: • ParentFragment is a fragment within a Navigation Graph, which has a SharedViewModel with some LiveData, and hosts a ViewPager2 • ChildAFragment is a fragment inserted into the ViewPager, which shows and changes some SharedViewModel's LiveData • ChildBFragment is another fragment inserted into the ViewPager, which shows and changes some SharedViewModel's LiveData So far so good, now the problem is: ParentFragment receives an argument. This argument should be in the ViewModel. Usually I would do:
Copy code
@HiltViewModel
class SomeViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
): ViewModel() {

    val argument: Argument =
        savedStateHandle[ParentFragmentArgs::argument.name]!!
}
However, this does not work with SharedViewModel (
Copy code
private val viewModel: SomeSharedViewModel by activityViewModels()
) I think I understand why. This ViewModel isn't scoped to the Fragment, but to the Activity, so it probably gets the savedState of the Activity instead of the Fragment's (right?)
i
Is there a reason you're scoping your ViewModel to your activity instead of to your parent fragment?
Copy code
private val viewModel: SomeSharedViewModel by viewModels({ requireParentFragment() })
🙌 1
t
Wow that was simple 😂 thanks so much 🙌