https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
a

allan.conda

04/15/2022, 5:05 PM
Struggling with multiple backstacks with compose routes... What would be the correct way to navigate to a destination that is in another tab? Let’s say A, J, X is the bottom bar top-level destinations, and this is the graph:
A -> B -> C
J -> K -> L
X -> Y -> Z
If app is in J, then it wants to go navigate to Y, how do I navigate to Y correctly? I just call
navController.navigate("Y")
, but then the bottom bar now behaves weirdly, tapping the J bottom bar does nothing. The bottom bar is showing because it’s logic for visibility is
currentDestination.hierarchy.any { it.route in bottomDestinations }
based on official docs and samples. Is there a better way?
i

Ian Lake

04/15/2022, 5:10 PM
You are in full control over the source of truth for what tab is selected if you don't want to use the navigation graph you are on as the source of truth (which is what the docs use)
a

allan.conda

04/15/2022, 5:22 PM
Thank you for the quick response 🙏 I see. I do want to use the navigation graph as source of truth. If I want to respect the graph definition, the valid navigation paths for J would be: A, X (via bottom bar), and K. Is that correct? Trying to add more context, my UseCase is like a notification list with notifications containing deeplinks which can basically navigate anywhere in the app which supports deeplinks. Would explicit deeplinks via PendingIntent be the right solution here? Assuming below would be a lot more complicated as it’s going against the docs.
You are in full control over the source of truth for what tab is selected
i

Ian Lake

04/15/2022, 5:25 PM
So are you...trying to add Y to the back stack associated with A (where you are at right now)? Or are you trying to swap to the back stack of X, then show Y? Those are very different things
a

allan.conda

04/15/2022, 5:33 PM
I imagine both could be valid use case within my context, but here let’s say I want to do the latter. Apologies if I have poor understanding how the back stack swapping works, I did try what you are describing I think, but it behaves weirdly, would you mind taking a little look at what may be wrong at my attempt at this?
navController.navigate("Y_navgraph") {
    popUpTo("J_navgraph") { // specifically J, as A seems to work (probably because it's startDestination)
        saveState = true
    }
    launchSingleTop = true
    restoreState = true
}
i

Ian Lake

04/15/2022, 5:35 PM
You most certainly want to do the exact same thing that you do for your bottom nav, including popping up to the same place
a

allan.conda

04/15/2022, 5:45 PM
I see. I hope you bear with me for a bit more as I think I’m getting really close to what I need. All my bottom bar basically have this logic:
navController.navigate("Y_navgraph") {
    popUpTo(navController.graph.findStartDestination().id) {  // basically A
        saveState = true
    }
    launchSingleTop = true
    restoreState = true
}
Doing so I’m not sure the Up & Back button works correctly. I kind of expect it to go to
X
which is the parent of
Y
in the graph, or going back to
J
seems right as well. But it seems to go back to A (the start destination). Is this as expected or am I still missing something? It’s a bit weird to me that
Y
gets navigated to as the startDestination of the
X
tab, I kind of expected the startDestination to be there…
i

Ian Lake

04/15/2022, 5:49 PM
I think you need to be more specific about what your actual back stacks are when you start and where you want them to be when you finish. If you've never navigated to 'X' before, then the
restoreState = true
isn't going to do anything - there's nothing to restore. You've navigated to 'Y', so you get 'Y' as the only destination on that stack, exactly what you told NavController to do
What happens if you have navigated to 'X' before? Do you want to destroy that stack (and its state) before you navigate to a fresh copy of it, starting with 'X', then 'Y'? You'd need to explicitly tell the NavController that's what you want to do:
// clear any previously saved stack on X
navController.clearBackStack("X")
// navigate to "X", swapping tabs
navController.navigate("X") {
  popUpTo(navController.graph.findStartDestination().id) {
    // Make sure to save the state of "J"
    saveState = true
  }
}
// Now add "Y" on top of X
navController.navigate("Y")
a

allan.conda

04/15/2022, 6:03 PM
I see! TIL about
clearBackStack(route)
which helped me understand
saveSate
better. So
saveState
saved a back stack tagged to the current route (
J
) before doing the
navigate(route) { popUpTo(…) }
operation. Then
restoreState
must be trying to restore the back stack of
navigate(X)
IIUC. And in above snippet we don’t want to restore the backstack hence we don’t set
restoreState=true
. I’m curious if
clearBackstack
here is necessary given we are not restoring `X`’s back stack anyway.
i

Ian Lake

04/15/2022, 6:05 PM
you probably still want to clear it out so that any existing
ViewModel
or saved state associated with those previous destinations is properly cleaned up
👍 1
a

allan.conda

04/15/2022, 6:06 PM
I see, do you mean that back stack remains available indefinitely and can still be accessed later even if I already navigated to
X
without restoring the state? assuming I don’t
saveState
from X again.
i

Ian Lake

04/15/2022, 6:09 PM
Yep, we talk a bit about that mental model of holding onto that stack separately in the deep dive blog post (in the context of fragments, but it works the same in Navigation): https://medium.com/androiddevelopers/multiple-back-stacks-b714d974f134
👀 1
:thank-you: 1
So if you don't override the saved back stack (by saving over it), restoring it, or clearing it, it'll just keep being saved
👍 1
a

allan.conda

04/15/2022, 6:11 PM
In my case, I do actually want to save the backstack (don’t want to reinit the ViewModel in X)
navController.navigate("X") {
    popUpTo(navController.graph.findStartDestination().id) {
        saveState = true
    }
    launchSingleTop = true
    restoreState = true
}
navController.navigate("Y")
And this one works nicely for me. Pressing Back from Y goes back to X, then X back to A.
Thank you so much for helping clarify this! I’ve been eyeing migrating to multiple backstack for some time (ever since that issue ticket was created) and only got the chance to attempt this now. We have been doing single backstack for a long time so I am used to thinking with that model. I know your time is very valuable. I will share this to my team and try to experiment a bit more with different use cases.