Member-only story
Jetpack Compose Navigation: Embracing Type Safety and Simplifying Parcelable Handling with NavHelper library

Resources
Full video tutorial: YouTube
At the above video you can watch how to embrace the new type safety provided by the new navigation libary, utilizing DataClass
to pass parameters, and how to fully add Parcelables
. Then the video shows a simplification using the NavHelper
library to pass your parcelables with almost no effort, almost as if Parcelables were primitives.
NavHelper Library at GitHub
Old way passing Parcellables through BackStack: GIST
New way passing Parcellables through BackStack: GIST
Demo Project at GitHub
Introduction
A crucial aspect of crafting seamless user experiences in Jetpack Compose is navigation, and with the release of Jetpack Compose Navigation 2.8.0-alpha08, we’ve witnessed a significant shift towards a more robust and type-safe approach, as announced at Google I/O ‘24.
In this article, we’ll delve into the world of type-safe navigation in Jetpack Compose, with a focus on passing Parcelables
, and introduce a handy helper library, NavHelper
, designed to simplify your navigation code.
The Landscape Before Type Safety
In the pre-type-safe era of Jetpack Compose Navigation, passing complex data like Parcelable
objects between composables posed a significant challenge. Developers often found themselves caught between two less-than-ideal approaches:
- Leveraging the Backstack for Parcelables: The backstack, a core component of navigation, served as a conduit for data transfer. However, it wasn’t designed to directly handle complex objects like
Parcelable
s. To work around this, developers would typically store these objects in theSavedStateHandle
associated with the backstack entry. While functional, this method came with caveats. It tightly coupled navigation logic to theSavedStateHandle
, making it less flexible and potentially leading to unexpected behavior if not managed carefully. Additionally, retrieving the data on the destination screen required extra steps and introduced some potential for errors…