How to pass navigation argument into ViewModel using Dagger Hilt?

82 Views Asked by At

I have a Single Activity App consisting of two List-Detail fragments

My navigation function looks like this:

private fun navigateToDetail(noteId: String?, transitionView: View) {
    val action = NotesFragmentDirections.actionNotesFragmentToNoteDetailFragment(
        noteId,
        transitionView.transitionName
    )
    val extras = FragmentNavigatorExtras(transitionView to transitionView.transitionName)
    findNavController().navigate(action, extras)
}

Here is my ViewModel in DetailFragment:

@HiltViewModel
class DetailViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val _state: MutableStateFlow<DetailState> = MutableStateFlow(DetailState())
    val state: StateFlow<DetailState> = _state.asStateFlow()

    init {
        savedStateHandle.get<String>("note_id")?.let { noteId ->
            getNote(noteId.toLong())
        }
    }
    ...

}

I have 2 cases, either I send an ID as an argument, in which case the parts fragment is filled in. Or I send null to open an empty parts screen. But for some reason in savedStateHandle the value is always null.

1

There are 1 best solutions below

2
ΓDΛ On

It's hard to understand the structure from your codes. However, I can show an example usage.

SharedViewModel

class SharedViewModel(private val stateHandle: SavedStateHandle) : ViewModel() {
    var data = stateHandle.getLiveData<String>("key")
}

FragmentA

findNavController().currentBackStackEntry?.savedStateHandle?.set("key", data)
findNavController().navigate(R.id.fragmentB)

FragmentB

sharedViewModel.data.observe(viewLifecycleOwner, Observer {
    
})

Note

private val sharedViewModel: SharedViewModel by activityViewModels()