Koin – SharedStateViewModel unexpected behavior

Hey, so I am working on a simple note app in which I am using Koin to learn it. In the app, there’s a NotesFragment that shows notes and InsertNotesFragment, that shows details of a clicked note or in which you can insert a new note.

In the InsertNotesFragment, there’s a button that also shows up a BottomSheetDialogFragment, in which one can select a color for a new/existing note.

InsertNotesFragment can be opened by clicking an existing note (note editing mode) or by clicking an add button in the NotesFragment (note inserting mode).

Now, InsertNotesFragment and BottomSheetDialogFragment are supposed to share a ViewModel with a StateFlow object that represents Note’s state.

Note class:

data class Note( val id: Int? = 0, val title: String? = "", val content: String? = "", val date: String? = "", val color: Int? = Color.parseColor("#ffffff") ) 

Note’s StateFlow in the shared view model:

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

It should work in a way that for example changing title or content text in InsertNotesFragment should update the note’s StateFlow “title” and “content” values and changing the color in BottomSheetDialogFragment should change the note’s StateFlow “color” value.

To share the viewModel instance, I am using Koin’s sharedStateViewModel, as I am injecting SavedStateHandle into the shared view model (so I can retrieve navigation arguments – I am passing id of the clicked note to load note’s details).

When I for example click the add button, the shared view model gets initialized. However, when I then press the back button and click the add button again, the screen (InsertNotesFragment) shows but the shared view model does not initialize again as I would expect – the view model instance stays alive for some reason. Not only that, the value passed in navigation arguments is never retrieved in the savedstatehandle. This is the way I am trying to get those arguments in viewmodel

val id = InsertNotesFragmentArgs.fromSavedStateHandle(savedStateHandle).noteId 

I don’t really know what I am doing wrong here. I’ve used saved state handle with Compose Navigation in the past this way and it worked great. I thought it would be the same with XML Navigation. I am also not sure why viewmodel persists when I close the InsertNotesFragment with a back press.

I am probably missing some knowledge that I am unaware of and I am not sure on how to fix this. If there’s someone who uses Koin regularly and could help me, it would be really appreciated.

submitted by /u/Gowreen
[link] [comments]