Type-safe arguments for JetPack Navigation Compose using Kotlinx.Serialization

Overview

Navigation Compose Typed

Compile-time type-safe arguments for JetPack Navigation Compose library. Based on KotlinX.Serialization.

Kiwi.com library CI Build GitHub release Maven release

Major features:

  • Complex types support, including nullability for primitive types - the only condition is that the type has to be serializable with KotlinX.Serializable library.
  • Based on official Kotlin Serialization compiler plugin - no slowdown with KSP nor KAPT.
  • All JetPack Navigation Compose features: e.g. navigateUp() after a deeplink preserves the top-level shared arguments.
  • Few simple functions, no new complex NavHost or NavController types; this allows covering other JetPack Navigation Compose extensions.
  • Gradual integration, feel free to onboard just a part of your app.

QuickStart

Add this library dependency and KotlinX.Serialization support

plugins {
	id("org.jetbrains.kotlin.plugin.serialization") version "1.7.10"
}
dependencies {
	implementation("com.kiwi.navigation-compose.typed:core:<version>")
	implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0")
}

Warning This library uses Semantic Versioning. Be aware that BC breaks are allowed in minor versions before the major 1.0 version.

Create app's destinations

import com.kiwi.navigationcompose.typed.Destination

sealed interface Destinations : Destination {
	@Serializable
	object Home : Destinations

	@Serializable
	data class Article(
		val id: String,
	) : Destinations
}

and use them in the navigation graph definition

import com.kiwi.navigationcompose.typed.composable
import com.kiwi.navigationcompose.typed.createRoutePattern

NavGraph(
	startDestination = createRoutePattern<Destinations.Home>(),
) {
	composable<Destinations.Home> {
		Home()
	}
	composable<Destinations.Article> {
		// this is Destinations.Article
		Article(id)
	}
}

Now, it is time to navigate! Create a Destination instance and pass it to the navigate extension method on the standard NavController.

import com.kiwi.navigationcompose.typed.Destination
import com.kiwi.navigationcompose.typed.navigate

@Composable
fun AppNavHost() {
	val navController = rememberNavController()
	NavGraph(
		navController = navController,
	) {
		composable<Destinations.Home> {
			Home(navController::navigate)
		}
	}
}

@Composable
private fun Home(
	onNavigate: (Destination) -> Unit,
) {
	Home(
		onArticleClick = { id -> onNavigate(Destinations.Article(id)) },
	)
}

@Composable
private fun Home(
	onArticleClick: (id: Int) -> Unit,
) {
	Column {
		Button(onClick = { onArticleClick(1) }) { Text("...") }
		Button(onClick = { onArticleClick(2) }) { Text("...") }
	}
}

Extensibility

What about cooperation with Accompanist's AnimatedNavHost or bottomSheet {}? Do not worry. Basically, all this are just few simple functions. Create your own abstraction and use createRoutePattern(), createNavArguments(), decodeArguments() and registerDestinationType() functions.

import com.kiwi.navigationcompose.typed.createRoutePattern
import com.kiwi.navigationcompose.typed.createNavArguments
import com.kiwi.navigationcompose.typed.decodeArguments
import com.kiwi.navigationcompose.typed.Destination
import com.kiwi.navigationcompose.typed.registerDestinationType

private inline fun <reified T : Destination> NavGraphBuilder.bottomSheet(
	noinline content: @Composable T.(NavBackStackEntry) -> Unit,
) {
	val serializer = serializer<T>()
	registerDestinationType(T::class, serializer)
	bottomSheet(
		route = createRoutePattern(serializer),
		arguments = createNavArguments(serializer),
	) {
		val arguments = decodeArguments(serializer, it)
		arguments.content(it)
	}
}

NavGraph {
	bottomSheet<Destinations.Article> {
		Article(id)
	}
}
Comments
  • Update androidGradlePlugin to v7.3.0

    Update androidGradlePlugin to v7.3.0

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | com.android.application (source) | 7.3.0-rc01 -> 7.3.0 | age | adoption | passing | confidence | | com.android.library (source) | 7.3.0-rc01 -> 7.3.0 | age | adoption | passing | confidence |


    Configuration

    πŸ“… Schedule: Branch creation - "before 3am on Monday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    β™» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    πŸ”• Ignore: Close this PR and you won't be reminded about these updates again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    chore 
    opened by renovate[bot] 0
  • Update dependency androidx.compose.compiler:compiler to v1.3.1

    Update dependency androidx.compose.compiler:compiler to v1.3.1

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | androidx.compose.compiler:compiler (source) | 1.3.0 -> 1.3.1 | age | adoption | passing | confidence |


    Configuration

    πŸ“… Schedule: Branch creation - "before 3am on Monday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    β™» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    πŸ”• Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    chore 
    opened by renovate[bot] 0
  • Update dependency com.vanniktech.maven.publish.base to v0.22.0

    Update dependency com.vanniktech.maven.publish.base to v0.22.0

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | com.vanniktech.maven.publish.base | 0.21.0 -> 0.22.0 | age | adoption | passing | confidence |


    Release Notes

    vanniktech/gradle-maven-publish-plugin

    v0.22.0

    Compare Source

    • NEW: When publishing to maven central by setting SONATYPE_HOST or calling publishToMavenCentral(...) the plugin will now explicitly create a staging repository on Sonatype. This avoids issues where a single build would create multiple repositories
    • The above change means that the plugin supports parallel builds and it is not neccessary anymore to use --no-parallel and --no-daemon together with publish
    • NEW: When publishing with the publish or publishAllPublicationsToMavenCentralRepository tasks the plugin will automatically close the staging repository at the end of the build if it was successful.
    • NEW: Option to also automatically release the staging repository after closing was susccessful
    SONATYPE_HOST=DEFAULT # or S01
    SONATYPE_AUTOMATIC_RELEASE=true
    

    or

    mavenPublishing {
      publishToMavenCentral("DEFAULT", true)
      // or publishToMavenCentral("S01", true)
    }
    
    • in case the option above is enabled, the closeAndReleaseRepository task is not needed anymore
    • when closing the repository fails the plugin will fail the build immediately instead of timing out
    • when closing the repository fails the plugin will try to print the error messages from Nexus
    • increased timeouts for calls to the Sonatype Nexus APIs
    • fixed incompatibility with the com.gradle.plugin-publish plugin
    • added wokaround for Kotlin multiplatform builds reporting disabled build optimizations

    Configuration

    πŸ“… Schedule: Branch creation - "before 3am on Monday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    β™» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    πŸ”• Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    chore 
    opened by renovate[bot] 0
  • Update dependency androidx.navigation:navigation-compose to v2.5.2

    Update dependency androidx.navigation:navigation-compose to v2.5.2

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | androidx.navigation:navigation-compose (source) | 2.5.1 -> 2.5.2 | age | adoption | passing | confidence |


    Configuration

    πŸ“… Schedule: Branch creation - "before 3am on Monday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    β™» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    πŸ”• Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    chore 
    opened by renovate[bot] 0
  • Update plugin kotlinter to v3.12.0

    Update plugin kotlinter to v3.12.0

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | org.jmailen.kotlinter | 3.11.1 -> 3.12.0 | age | adoption | passing | confidence |


    Configuration

    πŸ“… Schedule: Branch creation - "before 3am on Monday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    β™» Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    πŸ”• Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, click this checkbox.

    This PR has been generated by Mend Renovate. View repository job log here.

    semver:patch chore 
    opened by renovate[bot] 0
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    This repository currently has no open or pending branches.

    Detected dependencies

    github-actions
    .github/workflows/build.yml
    • actions/checkout v3
    • actions/setup-java v3
    • yutailang0119/action-android-lint v3.1.0
    • yutailang0119/action-android-lint v3.1.0
    .github/workflows/release-drafter.yml
    • release-drafter/release-drafter v5
    • actions/checkout v3
    .github/workflows/release.yml
    • actions/checkout v3
    • actions/setup-java v3
    • softprops/action-gh-release v1
    gradle
    gradle.properties
    settings.gradle.kts
    build.gradle.kts
    core/gradle.properties
    core/build.gradle.kts
    demo/build.gradle.kts
    gradle/libs.versions.toml
    • org.jetbrains.kotlin:kotlin-stdlib-jdk8 1.7.10
    • org.jetbrains.kotlinx:kotlinx-serialization-json 1.4.0
    • androidx.compose.compiler:compiler 1.3.1
    • androidx.compose.material:material 1.2.1
    • androidx.navigation:navigation-compose 2.5.2
    • junit:junit 4.13.2
    • org.robolectric:robolectric 4.8.2
    • com.android.library 7.3.0
    • com.android.application 7.3.0
    • org.jetbrains.kotlin.jvm 1.7.10
    • org.jetbrains.kotlin.android 1.7.10
    • org.jetbrains.kotlin.plugin.serialization 1.7.10
    • com.vanniktech.maven.publish.base 0.22.0
    • org.jmailen.kotlinter 3.12.0
    gradle-wrapper
    gradle/wrapper/gradle-wrapper.properties
    • gradle 7.5.1

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
    opened by renovate[bot] 0
Releases(v0.4.0)
Owner
Kiwi.com
Kiwi.com
Minecraft NBT support for kotlinx.serialization

knbt An implementation of Minecraft's NBT format for kotlinx.serialization. Technical information about NBT can be found here. Using the same version

Ben Woodworth 35 Oct 3, 2022
Android Parcelable support for the Kotlinx Serialization library.

Android Parcelable support for the Kotlinx Serialization library.

Christopher 49 Aug 29, 2022
CSV and FixedLength Formats for kotlinx-serialization

Module kotlinx-serialization-csv Serialize and deserialize ordered CSV and Fixed Length Format Files with kotlinx-serialization. Source code Docs Inst

Philip Wedemann 6 Aug 27, 2022
Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask

kotlinx-serialization-bitmask Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask. Example @Serializa

marie 2 May 29, 2022
Type-safe time calculations in Kotlin, powered by generics.

Time This library is made for you if you have ever written something like this: val duration = 10 * 1000 to represent a duration of 10 seconds(in mill

Kizito Nwose 953 Sep 11, 2022
Simple Android Library, that provides easy way to start the Activities with arguments.

Warning: Library is not maintained anymore. If you want to take care of this library, propose it via Pull Request. It needs adjustmensts for newer ver

Marcin MoskaΕ‚a 427 Sep 19, 2022
An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines.

one An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines. Feature Transform different data structs to one. {errorCode, d

ChengTao 29 Jul 24, 2022
Kotlinx-murmurhash - Kotlin Multiplatform (KMP) library for hashing using MurmurHash

kotlinx-murmurhash Kotlin Multiplatform (KMP) library for MurmurHash, a non-cryp

Gonçalo Silva 20 Sep 6, 2022
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Practical Kotlin Multiplatform on the Web λ³Έ μ €μž₯μ†ŒλŠ” μ½”ν‹€λ¦° λ©€ν‹°ν”Œλž«νΌ 기반 μ›Ή ν”„λ‘œκ·Έλž˜λ° μ›Œν¬μˆ(κ°•μ’Œ)을 μœ„ν•΄ μž‘μ„±λœ ν…œν”Œλ¦Ώ ν”„λ‘œμ νŠΈκ°€ μžˆλŠ” κ³³μž…λ‹ˆλ‹€. μ›Œν¬μˆ κ³Όμ •μ—μ„œ μ½”ν‹€λ¦° λ©€ν‹°ν”Œλž«νΌμ„ 기반으둜 ν”„λ‘ νŠΈμ—”λ“œ(front-end)λŠ” Ko

SpringRunner 7 Sep 20, 2022
Built with Jetpack compose, multi modules MVVM clean architecture, coroutines + flow, dependency injection, jetpack navigation and other jetpack components

RickAndMortyCompose - Work in progress A simple app using Jetpack compose, clean architecture, multi modules, coroutines + flows, dependency injection

Daniel Waiguru 9 Jul 13, 2022
Automatic CoroutineDispatcher injection and extensions for kotlinx.coroutines

Dispatch Utilities for kotlinx.coroutines which make them type-safe, easier to test, and more expressive. Use the predefined types and factories or de

Rick Busarow 131 Aug 29, 2022
Small Kafka Playground to play around with Test Containers, and KotlinX Coroutines bindings while reading Kafka Definite Guide V2

KafkaPlayground Small playground where I'm playing around with Kafka in Kotlin and the Kafka SDK whilst reading the Kafka book Definite Guide from Con

Simon Vergauwen 25 Sep 6, 2022
It is far easier to design a class to be thread-safe than to retrofit it for thread safety later

"It is far easier to design a class to be thread-safe than to retrofit it for thread safety later." (Brian Goetz - Java concurrency: Publisher: Addiso

Nguyα»…n Trường Thα»‹nh 3 Sep 6, 2022
A minimal notes application in Jetpack Compose with MVVM architecture. Built with components like DataStore, Coroutines, ViewModel, LiveData, Room, Navigation-Compose, Coil, koin etc.

Paper - A Minimal Notes App A minimal notes application in Jetpack Compose with MVVM architecture. Built with components like DataStore, Coroutines, V

Akshay Sharma 130 Sep 23, 2022
:octocat: Navigation toolbar is a slide-modeled UI navigation controller made by @Ramotion

NAVIGATION TOOLBAR Navigation toolbar is a Kotlin slide-modeled UI navigation controller. We specialize in the designing and coding of custom UI for M

Ramotion 803 Sep 7, 2022
A pluggable sealed API result type for modeling Retrofit responses.

A pluggable sealed API result type for modeling Retrofit responses.

Slack 628 Sep 2, 2022
Basic app to use different type of observables StateFlow, Flow, SharedFlow, LiveData, State, Channel...

stateflow-flow-sharedflow-livedata Basic app to use different type of observables StateFlow, Flow, SharedFlow, LiveData, State, Channel... StateFlow,

Raheem 4 Jul 24, 2022
Jetpack Compose, Kotlin, MVVM, Navigation Component, Hilt, Retrofit2

Jetpack-Compose-Blueprint Jetpack Compose, Kotlin, MVVM, Navigation Component, Hilt, Retrofit2 Apps Packages data : It contains all the data accessing

Jai Khambhayta 14 Jul 31, 2022
Includes jetpack compose, navigation, paging, hilt, retrofit, coil, coroutines, flow..

Nextflix-Composable A Clean Architecture App to show use of multi-module-architecture in a Jetpack Compose. The modules are as follow: app: Presentati

Talha Fakıoğlu 174 Sep 29, 2022