8

I want to pass some data using savedStateHandle from activity straight to fragment's viewModel.

In my activity I have:

navController.addOnDestinationChangedListener { controller, _, _ ->
    controller.currentBackStackEntry?.savedStateHandle?.set(
        "foo",
         "bar"
    )
}

So code in viewModel looks like:

MyViewModel(state: SavedStateHandle) : ViewModel() {

    init {
        state
            ?.getStateFlow("foo", "")
            ?.onEach { /* do something */ }
            ?.launchIn(viewModelScope)
    }

And for some reason expected bar value never get emitted.

I've checked in Fragment itself, and data is there:

val handle = findNavController().currentBackStackEntry?.savedStateHandle

handle?.getLiveData<String>("foo")?.observe(viewLifecycleOwner) {
    // here it is

}

But is there any possibility to pass data right to the viewModel's savedStateHandle? I believe should be, since navagrs are passed somehow.

user3119685
  • 101
  • 5

0 Answers0