One Off the Slack: Navigation Arguments and Compose

With Navigation for Compose, there is a new system for passing arguments, compared to any of the previous Navigation options. In effect, everything winds up being “stringly typed” and stuck in a path-style string (/user/$userId).

Ashar Khan found this out the hard way:

I’m getting this error while passing a parcelable as argument in navigation… I know @Ian Lake suggested using IDs but I don’t wanna bother with that right now for a sample app. How can I fix this?

Google’s Ian Lake then pointed to his previous comment on that subject, that Ashar mentioned in passing:

In general, this isn’t something you should consider doing: pass the ID of the item instead of the item itself. The route structure in Navigation Compose has the best analog with a restful web service profile/{id} not profile/{a whole set of fields representing a user's profile} which is essentially what passing a parcelable is doing

So, as noloman pointed out, we need to have something that can work with those IDs:

ok that means we are forced to use some sort of repository or cache or something from where the destination can fetch the object given its ID, right?

This is likely to work fine in simple situations and fail in lots of edge cases. There are simply too many APIs that we use from the framework that return Parcelable objects to us that, as a result, cannot be passed via Navigation for Compose. We can try to design our composables such that we can avoid needing navigation in those areas, but I expect that will have mixed success. Or, we may need to stuff the values into a ViewModel and retrieve them in the destination composable, which gets messy if the scope of this data does not match an existing ViewModel.

In time, we will come up with halfway-decent patterns, whether based on official Google guidance or simply “rough consensus and running code”. My hope is for the former, and soon, as otherwise bad patterns will dominate the Stack Overflows of the world.

Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!