Koin SharedStateViewModel – SavedStateHandle set to null

Issue

This Content is from Stack Overflow. Question asked by PetrHoracek

so in my app, I am using Koin for DI. The app in question is a simple note app and has 2 main fragments: NotesFragment, which shows all notes and InsertNoteFragment, which is used to insert new notes or update existing notes. The InsertNoteFragment has a sharedViewModel, which is shared with BottomSheetDialogFragment, which I use to pick a style for a new note.

Now, when I click a note in NotesFragment, I want to open in in the InsertNoteFragment, so it can be updated. Navigating to the note looks like this:

notesAdapter.setOnItemClickListener { note ->
    note.id?.let { id ->
        findNavController().navigate(
             NotesFragmentDirections.actionNotesFragmentToInsertNotesFragment(noteId = id)
        )
    }

enter image description here

When I debug this piece of code, it shows, that the onClick id value corresponds with the note’s ID value, so all is good here. The ID value, which I send as a navigation argument, is supposed to be saved in SavedStateHandle which I inject to InsertNoteViewModel (the one, that’s shared between InsertNoteFragment and BottomSheetDialogFragment)

class InsertNotesViewModel(
private val insertNoteUseCase: InsertNoteUseCase,
private val loadOneItemUseCase: LoadOneItemUseCase,
savedStateHandle: SavedStateHandle): ViewModel() {

private val _noteState = MutableStateFlow(Note())
val noteState: StateFlow<Note> = _noteState.asStateFlow()

init {
    println("ID ${savedStateHandle.get<Int>("noteId")}")
    savedStateHandle.get<Int>("noteId")?.let {
        if(it != 0){
            loadOneItem(it)
        }
    }
}

ViewModel is injected with Koin:

viewModel{ params ->
    InsertNotesViewModel(get(), get(), params.get())
}

to the InsertNoteFragment and BottomSheetDialogFragment with sharedStateViewModel (as is suggested in Koin Documentation: https://insert-koin.io/docs/reference/koin-android/viewmodel/)

private val viewModel by sharedStateViewModel<InsertNotesViewModel>()

The problem is that the SavedStateHandle id value is null every single time. I’ve tried to not use the lazy delegated injection (using getSharedStateViewModel()) but the result is the same. I’ve been using SavedStateHandle for this purpose before using Hilt and it worked just fine. Any ideas will be appreciated!



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?