Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
kroegerama opened this issue Oct 31, 2023 · 12 comments · Fixed by #102
Closed

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

kroegerama opened this issue Oct 31, 2023 · 12 comments · Fixed by #102
Labels
question Further information is requested

Comments

@kroegerama
Copy link

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?)

@kroegerama kroegerama changed the title How to access destination arguments in a ViewModel via the SavedStateHandle How to access destination arguments in a ViewModel via the SavedStateHandle? Oct 31, 2023
@StylianosGakis
Copy link

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
Copy link

@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
Copy link
Author

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
Copy link

jmhend commented Nov 14, 2023

+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
Copy link
Collaborator

hrach commented Nov 15, 2023

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 hrach added the question Further information is requested label Nov 15, 2023
@hrach
Copy link
Collaborator

hrach commented Nov 15, 2023

Why not read it from the state? My POV:

  • not well documented that this state contains the nav params
  • being explicit about VM "deps" is better than pass them through simple Map

@hrach
Copy link
Collaborator

hrach commented Nov 20, 2023

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

@hrach hrach closed this as completed Nov 20, 2023
@kroegerama
Copy link
Author

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
Copy link
Collaborator

hrach commented Nov 20, 2023

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.

@hrach hrach reopened this Nov 20, 2023
@kroegerama
Copy link
Author

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:

  • They access the SavedStateHandle here
  • Also, in their typesafe version, they use the SavedStateHandle as a constructor for the navigation arguments here

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
Copy link
Collaborator

hrach commented Nov 27, 2023

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

@StylianosGakis
Copy link

StylianosGakis commented Dec 5, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants