kiwicom / navigation-compose-typed

Type-safe arguments for Jetpack Navigation Compose using Kotlinx.Serialization
MIT License
220 stars 9 forks source link

How to access destination arguments in a ViewModel via the SavedStateHandle? #95

Closed kroegerama closed 10 months ago

kroegerama commented 11 months ago

I am currently migrating an app to use your library. I have compared a few typed navigation compose libraries and found your approach to be the best for my liking.

I have one question, though: How can I access the navigation arguments inside a ViewModel? The ViewModel is injected in my screens via viewModel: MyViewModel = hiltViewModel().

My ViewModel has the default handle: SavedStateHandle argument.

(Bonus question: What's the best way to create NavGraph-Scoped ViewModels using your library?)

StylianosGakis commented 11 months ago

For the bonus question. We do this https://github.com/HedvigInsurance/android/blob/082e966c5023ee9efaede2f5b61cc4df7b860d32/app/navigation/navigation-compose-typed/src/main/kotlin/com/hedvig/android/navigation/compose/typed/DestinationScopedViewModel.kt#L16-L25 It should just work, give it a shot. We use koin here of course, but edit it accordingly to use hilt instead. The core logic of this is to get the NavBackStackEntry through

val parentEntry: NavBackStackEntry = remember(navController, backStackEntry) {
  navController.getBackStackEntry(createRoutePattern<Dest>())
}

then I would guess that hiltViewModel also accepts it as a parameter to get the right scope

WildOrangutan commented 10 months ago

@kroegerama since library is only extension of Jetpack navigation for compose, you can access arguments from SavedStateHandle. The only issue is, how to access them in a type safe way.

If you for example look at quick start. Article destination has argument id. But to access it, I guess you would probably need to do savedStateHandle["id"]. Not ideal, since library has the key name "under control".

It would probably be nice to have additional extension, that parses arguments, based on destination arguments, if possible.

kroegerama commented 10 months ago

Oh yes, I am currently using the "raw" method to access the attributes:

    val args = MyNavArgs(
        handle["myId"]!!,
        handle.get<String>("myBoolean")!!.toBoolean()
    )

Especially, the myBoolean attribute is quite "ugly", so I was hoping for a typesafe alternative.

jmhend commented 10 months ago

+1 on this. I'm considering adopting this library, and giving SavedStateHandles the same type-safety afforded to Bundles in decoding would be super helpful.

Either that, or opening up a simple API for the underlying getSerializersModule() so we can write our own SavedStateHandler decoder.

Appreciate your work on this library! :D

hrach commented 10 months ago

I'm sorry for the late answer, I somehow missed this issue.

We explicitly pass the wanted navigation arguments to the viewModel through the parameters. In koin using parametersOf(), in Hilt using the assisted parameters. Usually, we pass the whole destination object.

import org.koin.androidx.compose.getViewModel

val viewModel: ProfileViewModel = getViewModel { parametersOf(destination) }
hrach commented 10 months ago

Why not read it from the state? My POV:

hrach commented 10 months ago

Closing as answered. If anything, don't hesitate to comment.

kroegerama commented 10 months ago

In my opinion, this library definitely needs a way to extract the destination classes from a SavedStateHandle. That's the only correct way to properly deal with process death, if I am not wrong.

Also, creating ViewModels with custom/assisted parameters seems a little bit like a hack for me. That way the parameters would be sent to the ViewModel twice, right? Once via the parameter, and once via the SavedStateHandle.

hrach commented 10 months ago

In my opinion, this library definitely needs a way to extract the destination classes from a SavedStateHandle. That's the only correct way to properly deal with process death, if I am not wrong.

The NavHost state is properly restored, the backstack entry is properly decoded and the VM is properly created using those nav params. So my answer is: No, this is not the only correct way.

creating ViewModels with custom/assisted parameters seems a little bit like a hack for me

I disagree, I believe the VM inputs should be clear and not hidden in a map. SavedStateHandle is an implementation detail of state retention, not an ideal way to provide necessary inputs.


But ok, let's be open-minded here - is this feature documented anywhere - I mean - is there a contract that promises SavedStateHandle to contain navigation inputs? If so, I'm very ok to add it. If not, I am open to giving you the possibility.

kroegerama commented 10 months ago

Thanks for reopening the issue. I really appreciate it.

I'm not sure, if you could count that as documented feature, but google is using this in their official docs:

However, this is your library after all. And if this is against your typical use cases, I can completely see, why you do not want (or have the time) to implement it. It's just that I really like this library and that's the only nice-to-have feature it's missing for me. (As a side note: I also was able to create a custom navigator that uses the new BottomSheet from Material 3, without the accompanist library - your library made this very easy for me)

hrach commented 10 months ago

fun SavedStateHandle.decodeArguments<T>() released in 0.9

StylianosGakis commented 10 months ago

Might wanna edit that last message to say decodeArguments so that people don't become confused when they can't find decoredArguments :D