Jetpack Navigation 3 is a new Google navigation library that is fundamentally different from previous versions. The main idea of Nav3 is simple: you have a NavBackStack — a regular mutable list where each element represents a screen in your application.Jetpack Navigation 3 is a new Google navigation library that is fundamentally different from previous versions. The main idea of Nav3 is simple: you have a NavBackStack — a regular mutable list where each element represents a screen in your application.

Nav3 Router: Convenient Navigation on Top of Jetpack Navigation 3

2025/09/17 20:00

What is Jetpack Navigation 3?

Jetpack Navigation 3 is a new Google navigation library that is fundamentally different from previous versions. The main idea of Nav3 is simple: you have a NavBackStack — a regular mutable list where each element represents a screen in your application.

\ You add and remove elements from this list, and the UI automatically updates. Each screen is represented as a NavKey — a regular Kotlin class.

\ This gives you full control over navigation, but requires writing quite a lot of boilerplate code for typical operations.

Why Working Directly with NavBackStack is Inconvenient

Let's look at what the code looks like when working directly with NavBackStack:

@Composable fun MyApp() {     val backStack = rememberNavBackStack(Screen.Home)      // Add a screen     backStack.add(Screen.Details("123"))      // Go back     backStack.removeLastOrNull()      // Replace current screen     backStack.set(backStack.lastIndex, Screen.Success) } 

Problems begin when you need to trigger navigation from a ViewModel. You'll have to either pass NavBackStack to the ViewModel (which, in my understanding, violates architectural principles, as I believe the ViewModel shouldn't know about Compose-specific things), or create intermediate callbacks for each navigation action.

\ Additionally, when working with the stack directly, it's easy to forget to handle edge cases.

How Nav3 Router Simplifies the Work

Nav3 Router is a thin wrapper over Navigation 3 that provides a familiar API for navigation. Instead of thinking about indices and list operations, you simply say "go to screen X" or "go back."

\ Important point: Nav3 Router doesn't create its own stack. It works with the same NavBackStack that Navigation 3 provides, just making it more convenient to work with. When you call router.push(Screen.Details), the library translates this into the corresponding operation with the original stack.

\ Main advantages:

  • Can be used from ViewModel
  • Navigation commands are buffered if UI is temporarily unavailable (for example, during screen rotation)
  • All stack operations happen atomically
  • Clear API
  • Flexibility in modification and adding custom behavior

Installation

Nav3 Router is available on Maven Central. Add the dependency to your build.gradle.kts:

// For shared module in KMP project kotlin {     sourceSets {         commonMain.dependencies {             implementation("io.github.arttttt.nav3router:nav3router:1.0.0")         }     } }  // For Android-only project dependencies {     implementation("io.github.arttttt.nav3router:nav3router:1.0.0") } 

\ The library source code is available on GitHub: github.com/arttttt/Nav3Router

How Nav3 Router is Structured

The library consists of three main parts, each solving its own task:

Router — Developer Interface

Router provides methods like push(), pop(), replace(). When you call these methods, Router creates corresponding commands and sends them down the chain. Router itself knows nothing about how navigation will be executed — this allows using it from anywhere.

CommandQueue — Buffer Between Commands and Their Execution

CommandQueue solves the timing problem. Imagine: the user pressed a button during screen rotation. The UI is being recreated, and the navigator is temporarily unavailable. CommandQueue will save the command and execute it as soon as the navigator is ready again. Without this, the command would simply be lost.

// Simplified queue logic class CommandQueue<T : Any> {     private var navigator: Navigator<T>? = null     private val pending = mutableListOf<Command<T>>()      fun executeCommand(command: Command<T>) {         if (navigator != null) {             navigator.apply(command)  // Navigator exists - execute immediately         } else {             pending.add(command)       // No - save for later         }     } } 

Navigator takes commands and applies them to NavBackStack. Important detail: it first creates a copy of the current stack, applies all commands to it, and only then atomically replaces the original stack with the modified copy. This guarantees that the UI will never see intermediate stack states.

// Simplified Navigator logic fun applyCommands(commands: Array<Command>) {     val stackCopy = backStack.toMutableList()  // Work with a copy      for (command in commands) {         when (command) {             is Push -> stackCopy.add(command.screen)             is Pop -> stackCopy.removeLastOrNull()             // ... other commands         }     }      backStack.swap(stackCopy)  // Atomically apply changes } 

Getting Started With Nav3 Router

The simplest way — don't even create Router manually. Nav3Host will do it for you:

@Composable fun App() {     val backStack = rememberNavBackStack(Screen.Home)      // Nav3Host will create Router automatically     Nav3Host(backStack = backStack) { backStack, onBack, router ->         NavDisplay(             backStack = backStack,             onBack = onBack,             entryProvider = entryProvider {                 entry<Screen.Home> {                     HomeScreen(                         onOpenDetails = {                              router.push(Screen.Details)  // Use router                         }                     )                 }                  entry<Screen.Details> {                     DetailsScreen(                         onBack = { router.pop() }                     )                 }             }         )     } } 

For more complex applications, it makes sense to create a Router through DI and pass it to the ViewModel:

\ Define screens

@Serializable sealed interface Screen : NavKey {     @Serializable     data object Home : Screen      @Serializable     data class Product(val id: String) : Screen      @Serializable     data object Cart : Screen } 

\ Pass router to Nav3Host.

@Composable fun App() {     val backStack = rememberNavBackStack(Screen.Home)     val router: Router<Screen> = getSomehowUsingDI()      // Pass Router to Nav3Host     Nav3Host(         backStack = backStack,         router = router,     ) { backStack, onBack, _ ->         NavDisplay(             backStack = backStack,             onBack = onBack,             entryProvider = entryProvider {                 entry<Screen.Home> { HomeScreen() }                 entry<Screen.Details> { DetailsScreen() }             }         )     } } 

\ ViewModel receives Router through constructor.

class ProductViewModel(     private val router: Router<Screen>,     private val cartRepository: CartRepository ) : ViewModel() {      fun addToCart(productId: String) {         viewModelScope.launch {             cartRepository.add(productId)             router.push(Screen.Cart)  // Navigation from ViewModel         }     } } 

\ In UI, just use ViewModel.

@Composable fun ProductScreen(viewModel: ProductViewModel = koinViewModel()) {     Button(onClick = { viewModel.addToCart(productId) }) {         Text("Add to Cart")     } } 

Examples of Typical Scenarios

Simple Forward-Back Navigation

// Navigate to a new screen router.push(Screen.Details(productId))  // Go back router.pop()  // Navigate with replacement of current screen (can't go back) router.replaceCurrent(Screen.Success) 

Working with Screen Chains

// Open multiple screens at once router.push(     Screen.Category("electronics"),     Screen.Product("laptop-123"),     Screen.Reviews("laptop-123") )  // Return to a specific screen // Will remove all screens above Product from the stack router.popTo(Screen.Product("laptop-123")) 

Checkout Scenario

@Composable fun CheckoutScreen(router: Router<Screen>) {     Button(         onClick = {             // After checkout we need to:             // 1. Show confirmation screen             // 2. Prevent going back to cart              router.replaceStack(                 Screen.Home,                 Screen.OrderSuccess(orderId)             )             // Now only Home and OrderSuccess are in the stack         }     ) {         Text("Place Order")     } } 

Exiting Nested Navigation

// User is deep in settings: // Home -> Settings -> Account -> Privacy -> DataManagement  // "Done" button should return to home Button(     onClick = {         // Will leave only root (Home)         router.clearStack()     } ) {     Text("Done") }  // Or if you need to close the app from anywhere Button(     onClick = {         // Will leave only current screen and trigger system back         router.dropStack()     } ) {     Text("Exit") } 

Bonus: SceneStrategy and Dialogs

So far, we've only talked about simple navigation between screens. But what if you need to show a dialog or bottom sheet? This is where the SceneStrategy concept from Navigation 3 comes to help.

What is SceneStrategy?

SceneStrategy is a mechanism that determines exactly how screens from your stack will be displayed. By default, Navigation 3 uses SinglePaneSceneStrategy, which simply shows the last screen from the stack. But you can create your own strategies for more complex scenarios.

\ Think of SceneStrategy as a director who looks at your stack of screens and decides: "Okay, these three screens we show normally, but this last one — as a modal window on top of the previous ones". This allows representing different UI patterns with the same stack.

Creating a Strategy for ModalBottomSheet

Let's create a strategy that will show certain screens as bottom sheets. First, let's define how we'll mark such screens:

@Serializable sealed interface Screen : NavKey {     @Serializable     data object Home : Screen      @Serializable     data class Product(val id: String) : Screen      // This screen will be shown as bottom sheet     @Serializable     data object Filters : Screen } 

\ Now, let's create the strategy itself. It will check the metadata of the last screen and, if it finds a special marker, show it as a bottom sheet:

class BottomSheetSceneStrategy<T : Any> : SceneStrategy<T> {      companion object {         // Metadata key by which we identify bottom sheet         private const val BOTTOM_SHEET_KEY = "bottomsheet"          // Helper function to create metadata         fun bottomSheet(): Map<String, Any> {             return mapOf(BOTTOM_SHEET_KEY to true)         }     }      @Composable     override fun calculateScene(         entries: List<NavEntry<T>>,         onBack: (Int) -> Unit     ): Scene<T>? {         val lastEntry = entries.lastOrNull() ?: return null          // Check if the last screen has bottom sheet marker         val isBottomSheet = lastEntry.metadata[BOTTOM_SHEET_KEY] as? Boolean          if (isBottomSheet == true) {             // Return special Scene for bottom sheet             return BottomSheetScene(                 entry = lastEntry,                 previousEntries = entries.dropLast(1),                 onBack = onBack             )         }          // This is not a bottom sheet, let another strategy handle it         return null     } } 

Combining Multiple Strategies

In a real application, you might need bottom sheets, dialogs, and regular screens. For this, you can create a delegate strategy that will choose the right strategy for each screen:

class DelegatedScreenStrategy<T : Any>(     private val strategyMap: Map<String, SceneStrategy<T>>,     private val fallbackStrategy: SceneStrategy<T> ) : SceneStrategy<T> {      @Composable     override fun calculateScene(         entries: List<NavEntry<T>>,         onBack: (Int) -> Unit     ): Scene<T>? {         val lastEntry = entries.lastOrNull() ?: return null          // Check all keys in metadata         for (key in lastEntry.metadata.keys) {             val strategy = strategyMap[key]             if (strategy != null) {                 // Found suitable strategy                 return strategy.calculateScene(entries, onBack)             }         }          // Use default strategy         return fallbackStrategy.calculateScene(entries, onBack)     } } 

Using in Application

Now, let's put it all together. Here's what using bottom sheet looks like in a real application:

@Composable fun ShoppingApp() {     val backStack = rememberNavBackStack(Screen.Home)     val router = rememberRouter<Screen>()      Nav3Host(         backStack = backStack,         router = router     ) { backStack, onBack, router ->         NavDisplay(             backStack = backStack,             onBack = onBack,             // Use our combined strategy             sceneStrategy = DelegatedScreenStrategy(                 strategyMap = mapOf(                     "bottomsheet" to BottomSheetSceneStrategy(),                     "dialog" to DialogSceneStrategy()  // Navigation 3 already has this strategy                 ),                 fallbackStrategy = SinglePaneSceneStrategy()  // Regular screens             ),             entryProvider = entryProvider {                 entry<Screen.Home> {                     HomeScreen(                         onOpenFilters = {                             // Open filters as bottom sheet                             router.push(Screen.Filters)                         }                     )                 }                  entry<Screen.Product> { screen ->                     ProductScreen(productId = screen.id)                 }                  // Specify that Filters should be bottom sheet                 entry<Screen.Filters>(                     metadata = BottomSheetSceneStrategy.bottomSheet()                 ) {                     FiltersContent(                         onApply = { filters ->                             // Apply filters and close bottom sheet                             applyFilters(filters)                             router.pop()                         }                     )                 }             }         )     } } 

\ What's happening here? When you call router.push(Screen.Filters), the screen is added to the stack as usual. But thanks to metadata and our strategy, the UI understands that this screen needs to be shown as a bottom sheet on top of the previous screen, rather than replacing it completely.

\ When calling router.pop() the bottom sheet will close, and you'll return to the previous screen. From Router's point of view, this is regular back navigation, but visually it looks like closing a modal window.

Advantages of This Approach

Using SceneStrategy provides several important advantages. First, your navigation logic remains simple — you still use push and pop without thinking about how exactly the screen will be shown. Second, navigation state remains consistent — bottom sheet is just another screen in the stack that is properly saved during screen rotation or process kill. And finally, it provides great flexibility — you can easily change how a screen is displayed by just changing its metadata, without touching the navigation logic.

\ This approach is especially useful when the same screen can be shown differently depending on context. For example, a login screen can be a regular screen on first app launch and a modal dialog when attempting to perform an action that requires authorization.

Why You Should Use Nav3 Router

Nav3 Router doesn't try to replace Navigation 3 or add new features. Its task is to make working with navigation convenient and predictable. You get a simple API that can be used from any layer of the application, automatic handling of timing issues, and the ability to easily test navigation logic.

\ At the same time, under the hood, regular Navigation 3 still works with all its capabilities: state saving, animation support, and proper handling of the system "Back" button.

\ If you're already using Navigation 3 or planning to migrate to it, Nav3 Router will help make this experience more pleasant without adding unnecessary complexity to the project.

  • GitHub repository: github.com/arttttt/Nav3Router
  • Usage examples: see sample folder in the repository

\

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact [email protected] for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Lovable AI’s Astonishing Rise: Anton Osika Reveals Startup Secrets at Bitcoin World Disrupt 2025

Lovable AI’s Astonishing Rise: Anton Osika Reveals Startup Secrets at Bitcoin World Disrupt 2025

BitcoinWorld Lovable AI’s Astonishing Rise: Anton Osika Reveals Startup Secrets at Bitcoin World Disrupt 2025 Are you ready to witness a phenomenon? The world of technology is abuzz with the incredible rise of Lovable AI, a startup that’s not just breaking records but rewriting the rulebook for rapid growth. Imagine creating powerful apps and websites just by speaking to an AI – that’s the magic Lovable brings to the masses. This groundbreaking approach has propelled the company into the spotlight, making it one of the fastest-growing software firms in history. And now, the visionary behind this sensation, co-founder and CEO Anton Osika, is set to share his invaluable insights on the Disrupt Stage at the highly anticipated Bitcoin World Disrupt 2025. If you’re a founder, investor, or tech enthusiast eager to understand the future of innovation, this is an event you cannot afford to miss. Lovable AI’s Meteoric Ascent: Redefining Software Creation In an era where digital transformation is paramount, Lovable AI has emerged as a true game-changer. Its core premise is deceptively simple yet profoundly impactful: democratize software creation. By enabling anyone to build applications and websites through intuitive AI conversations, Lovable is empowering the vast majority of individuals who lack coding skills to transform their ideas into tangible digital products. This mission has resonated globally, leading to unprecedented momentum. The numbers speak for themselves: Achieved an astonishing $100 million Annual Recurring Revenue (ARR) in less than a year. Successfully raised a $200 million Series A funding round, valuing the company at $1.8 billion, led by industry giant Accel. Is currently fielding unsolicited investor offers, pushing its valuation towards an incredible $4 billion. As industry reports suggest, investors are unequivocally “loving Lovable,” and it’s clear why. This isn’t just about impressive financial metrics; it’s about a company that has tapped into a fundamental need, offering a solution that is both innovative and accessible. The rapid scaling of Lovable AI provides a compelling case study for any entrepreneur aiming for similar exponential growth. The Visionary Behind the Hype: Anton Osika’s Journey to Innovation Every groundbreaking company has a driving force, and for Lovable, that force is co-founder and CEO Anton Osika. His journey is as fascinating as his company’s success. A physicist by training, Osika previously contributed to the cutting-edge research at CERN, the European Organization for Nuclear Research. This deep technical background, combined with his entrepreneurial spirit, has been instrumental in Lovable’s rapid ascent. Before Lovable, he honed his skills as a co-founder of Depict.ai and a Founding Engineer at Sana. Based in Stockholm, Osika has masterfully steered Lovable from a nascent idea to a global phenomenon in record time. His leadership embodies a unique blend of profound technical understanding and a keen, consumer-first vision. At Bitcoin World Disrupt 2025, attendees will have the rare opportunity to hear directly from Osika about what it truly takes to build a brand that not only scales at an incredible pace in a fiercely competitive market but also adeptly manages the intense cultural conversations that inevitably accompany such swift and significant success. His insights will be crucial for anyone looking to understand the dynamics of high-growth tech leadership. Unpacking Consumer Tech Innovation at Bitcoin World Disrupt 2025 The 20th anniversary of Bitcoin World is set to be marked by a truly special event: Bitcoin World Disrupt 2025. From October 27–29, Moscone West in San Francisco will transform into the epicenter of innovation, gathering over 10,000 founders, investors, and tech leaders. It’s the ideal platform to explore the future of consumer tech innovation, and Anton Osika’s presence on the Disrupt Stage is a highlight. His session will delve into how Lovable is not just participating in but actively shaping the next wave of consumer-facing technologies. Why is this session particularly relevant for those interested in the future of consumer experiences? Osika’s discussion will go beyond the superficial, offering a deep dive into the strategies that have allowed Lovable to carve out a unique category in a market long thought to be saturated. Attendees will gain a front-row seat to understanding how to identify unmet consumer needs, leverage advanced AI to meet those needs, and build a product that captivates users globally. The event itself promises a rich tapestry of ideas and networking opportunities: For Founders: Sharpen your pitch and connect with potential investors. For Investors: Discover the next breakout startup poised for massive growth. For Innovators: Claim your spot at the forefront of technological advancements. The insights shared regarding consumer tech innovation at this event will be invaluable for anyone looking to navigate the complexities and capitalize on the opportunities within this dynamic sector. Mastering Startup Growth Strategies: A Blueprint for the Future Lovable’s journey isn’t just another startup success story; it’s a meticulously crafted blueprint for effective startup growth strategies in the modern era. Anton Osika’s experience offers a rare glimpse into the practicalities of scaling a business at breakneck speed while maintaining product integrity and managing external pressures. For entrepreneurs and aspiring tech leaders, his talk will serve as a masterclass in several critical areas: Strategy Focus Key Takeaways from Lovable’s Journey Rapid Scaling How to build infrastructure and teams that support exponential user and revenue growth without compromising quality. Product-Market Fit Identifying a significant, underserved market (the 99% who can’t code) and developing a truly innovative solution (AI-powered app creation). Investor Relations Balancing intense investor interest and pressure with a steadfast focus on product development and long-term vision. Category Creation Carving out an entirely new niche by democratizing complex technologies, rather than competing in existing crowded markets. Understanding these startup growth strategies is essential for anyone aiming to build a resilient and impactful consumer experience. Osika’s session will provide actionable insights into how to replicate elements of Lovable’s success, offering guidance on navigating challenges from product development to market penetration and investor management. Conclusion: Seize the Future of Tech The story of Lovable, under the astute leadership of Anton Osika, is a testament to the power of innovative ideas meeting flawless execution. Their remarkable journey from concept to a multi-billion-dollar valuation in record time is a compelling narrative for anyone interested in the future of technology. By democratizing software creation through Lovable AI, they are not just building a company; they are fostering a new generation of creators. His appearance at Bitcoin World Disrupt 2025 is an unmissable opportunity to gain direct insights from a leader who is truly shaping the landscape of consumer tech innovation. Don’t miss this chance to learn about cutting-edge startup growth strategies and secure your front-row seat to the future. Register now and save up to $668 before Regular Bird rates end on September 26. To learn more about the latest AI market trends, explore our article on key developments shaping AI features. This post Lovable AI’s Astonishing Rise: Anton Osika Reveals Startup Secrets at Bitcoin World Disrupt 2025 first appeared on BitcoinWorld.
Share
Coinstats2025/09/17 23:40