I feel like I'm going crazy, but I can't find docs...
# compose
c
I feel like I'm going crazy, but I can't find docs on how Compose + Hilt + AAC ViewModels can work together to pass arguments into a view model? I'm working on a typical list -> detail app, and I can't figure out how to pass an id from my NavHost to the new DetailScreen.
solved 1
f
You can retrieve the arguments directly inside the ViewModel from the SavedStateHandle
c
Yeah, that's what I was doing with fragments, but how do I pass the arg to the VM? The example only shows how to pass the arg to the composable
s
Dagger has assisted injection
c
@Florian do you have any link to "retrieve the arguments directly inside the ViewModel from the SavedStateHandle"? I don't see that anywhere in the link.
@Scott Kruse I'm using hilt and I know hilt provides fragment args via savedStateHandle without using assistedInjection, so that's why I'm asking if there's something like that for compose.
Alright, I got it in case anyone else is wondering. It does end up working with SavedStateHandle (even though the first time I tried it I swear it didn't work). /shrug My destination
Copy code
composable("detail/{id}") { MyDetailScreen() }
Composable
Copy code
@Composable
fun MyDetailScreen(
    vm: MyDetailViewModel = hiltViewModel(),
) {
ViewModel
Copy code
@HiltViewModel
class MyDetailViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle
) : ViewModel() {
    savedStateHandle.get<String>("id").orEmpty()
o
Does the same trick work with Koin?
f
@Colton Idle yes you just have to use the same id. I don't know why it's so badly documented.
you can also retrieve it as livedata
c
I feel like it's documented well with fragments, but I was looking for this in compose and it seemed lacking.
d
I had an issue related to
SavedStateHandle
too. Turns out after digging a lot into it, Ian Lake does mention that in a video from the Google I/O and also gives an example:

https://youtu.be/0z_dwBGQQWQ?t=987

One of the Jetpack Compose samples is also using
SavedStateHandle
. https://github.com/android/compose-samples/blob/22eea87c898c8cc76e0c1042274e0962f0[…]java/androidx/compose/samples/crane/details/DetailsViewModel.kt I really had a hard time figuring that out. I should mention that I'm now trying to save some data to the
SavedStateHandle
, but it looks like the
SavedStateHandle
is not restored once my ViewModel is used again even though I'm using
hiltViewModel(backStackEntry)
in my nav graph. So I still haven't figured that part yet and I have to say documentation would help a lot.
f
I think the backstack entry and the viewmodel have different SavedStateHandles/SavedInstanceStates
d
This clearly shows there's an issue with the documentation unfortunately.
f
I tried putting a value into the backstack entry of a destination and it didn't appear in that destination's ViewModel
but nav arguments do