Streamlining Navigation in Jetpack Compose

When compared with classic Android, Jetpack Compose — along with its declarative ways of building UI — brings a ton of new approaches to handle common tasks with great efficiency .
Navigation is one such area where compose has amazed me quite a lot. Its Navigation library allows us to navigate between composables without caring about fragments, dialogs, transaction managers and various other complex stuff. This is nothing less than a blessing!
Motivation
It provides us abilities to navigate to composables, pass data as arguments, consume deep links and much more. But if we don’t manage it properly, the code gets messy very quickly and it becomes difficult to understand.

Here’s an example :

There are various approaches and guidelines designed by experts to tackle this problem. But I decided to reinvent the wheel as per my needs. Assuming that you’re already aware about basics of Navigation with Compose, let’s dive into the solution.
Solution
To simplify things, I decided to build a helper class wherein we can define all the constants for routes & arguments. I call it NavHelper.kt
.
Route
It contains an abstract class called Route
which acts as a parent for all navigation graphs as well as consumables
It contains various properties and a member function. Let’s look at each of them in details.
label
is used to uniquely identify a composable or a nested grapharguments
&optionalArguments
are lists to accepts respective keys that will be used for mapping argumentsroute
useslabel
,arguments
&optionalArguments
to construct a string as per required syntax which can be used to define a route of a composable in the navigation graphaddress
is a function which takes a map of arguments as the parameter and returns a string which is constructed based onroute
and provided arguments. This is to be used when navigating to a composable.
To see the solution in action, let’s look at a use case.
Implementation
Let’s consider the following use case :

Let’s try to build such a navigation graph normally i.e. without using NavHelper.kt
:
As seen in the code snippet, there is a lot of repetition and mess. This is error prone only with 2 screens. Image the mess in the app with 30-40 screens!
Now, for the same use case, let’s use NavHelper.kt
that we created :
It looks clean and easy to understand. Under the hood, all the navigation logic in handled by NavHelper.kt
.
Here’s what I did inside NavHelper.kt
for this case.
This can be used as a launchpad for streamlining the entire navigation process and can probably still be optimised further.
Winding up
Here’s a sample codebase for you to experiment.
This is just an attempt to make things easier with navigation in Jetpack Compose. If you find any flaws/obstacles with this approach or if you know a better/simpler approach, please do let me know.
Please don’t forget to smash the Clap button if you found the article useful. See you next time! :)