https://kotlinlang.org logo
Join the conversationJoin Slack
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
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
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
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 Linen
compose
  • s

    Shakil Karim

    07/23/2021, 12:12 PM
    Is there any way to mark External classes as
    @Stable
    ?, I'm using MemoryCache.Key from Coil as a parameter to Composable Function, but not sure if by default it's considered Stable.
    d
    • 2
    • 4
  • g

    Gleno

    07/23/2021, 12:44 PM
    Are
    @Preview
    annotated functions stripped from final binary?
    b
    t
    r
    • 4
    • 11
  • g

    Gleno

    07/23/2021, 12:45 PM
    Also, is it possible to render a
    @Preview
    annotated function to a pdf or png?
    a
    d
    • 3
    • 4
  • a

    Adib Faramarzi

    07/23/2021, 1:18 PM
    https://twitter.com/TheSNAKY/status/1418561082378145796?s=20
    👍 2
    🙌🏻 1
    🙌 3
    • 1
    • 1
  • a

    Adib Faramarzi

    07/23/2021, 1:18 PM
    https://twitter.com/TheSNAKY/status/1418561093790748672?s=20
    🙌🏾 1
    🙌🏻 1
    🙌 4
    t
    • 2
    • 2
  • j

    julioromano

    07/23/2021, 1:57 PM
    Is there a way, for debugging purposes, to log when a composable function is being called as first composition and as a recomposition?
    ✅ 1
    👍 1
    a
    • 2
    • 1
  • c

    Colton Idle

    07/23/2021, 2:02 PM
    Am I doing anything wrong here? Can't get
    viewModel()
    to compile. I've added the lifecycle compose vm dependency
    i
    s
    k
    • 4
    • 22
  • r

    Rob

    07/23/2021, 5:48 PM
    I'm getting a
    java.lang.ClassCastException: java.lang.String cannot be cast to com.example.myapplication.MyId
    when unwrapping boxed value classes in compose
    collectAsState
    . I'm not sure if this a Compose bug or a Kotlin bug. Where should I report this?
    Untitled.cpp
    c
    • 2
    • 1
  • c

    Colton Idle

    07/23/2021, 6:35 PM
    I'm using Hilt, Compose, compose-navigation and I can't get a ViewModel to inject an object that I provide UNLESS I provide it via hiltViewModel. Is that purposeful? Code in thread.
    j
    h
    • 3
    • 7
  • c

    Colton Idle

    07/23/2021, 8:05 PM
    Trying to get compose + hilt + compose navigation working for a single activity app that has your typical logged in and logged out screens. Currently I see that my HomeScreen gets loaded twice? Am I doing something wrong? Code in thread.
    2021-07-23 16:00:13.146 4110-4110/com.rollertoaster.app E/mylog: logged in
    2021-07-23 16:00:13.218 4110-4110/com.rollertoaster.app E/mylog: logged in
    a
    i
    • 3
    • 15
  • c

    Chris Fillmore

    07/23/2021, 8:51 PM
    What’s the right way to handle
    onNewIntent()
    when using Compose Navigation? My use case is similar to e.g. OAuth authorization flow. I am redirecting back to an Activity via <intent-filter>, and starting the Activity with SINGLE_TOP. There will be a route in the new Intent, which I want to navigate to. Has anyone handled something like this? Here’s some dummy code example of what I mean:
    class MyActivity {
      
      fun onCreate() {
        setContent { MyApp() }
      }
    
      fun onNewIntent(intent: Intent) {
        val route = intent.getStringExtra("redirect_route")
        ?? What to do with 'route'
      }
    }
    
    @Composable
    fun MyApp() {
      val navController = rememberNavController()
      MyNavHost(navController)
    }
    
    @Composable
    fun MyNavHost(controller: NavController) {
      NavHost(...) {
        ... define routes ...
      }
    }
    a
    i
    • 3
    • 16
  • t

    Tash

    07/23/2021, 10:51 PM
    Is there an easy way to extend the click area of a
    Button
    , apart from creating physical padding around it by enclosing it in a
    Box
    etc ?
    👍 2
    a
    t
    • 3
    • 6
  • a

    Anton Dmytryshyn

    07/24/2021, 7:46 AM
    When setting the peek height of a bottom sheet scaffold, how do I set it to be 20% of the screen height at initialization?
    a
    • 2
    • 1
  • m

    ms

    07/24/2021, 9:00 AM
    recently I upgraded to Gradle 7.1.0-alpha04, but that has an issue where I can't run my app. Now I'm trying to revert back to alpha03 but AS is forcing me to use alpha04 with
    Android Gradle Plugin Upgrade Assistant
    dialog Dialog says
    This project is using version 7.1.0-alpha03 of the Android Gradle plugin, which is incompatible with this version of Android Studio.
    Using AS Canary 4
    s
    • 2
    • 2
  • m

    Mohan

    07/24/2021, 11:26 AM
    I have a usecase when item of lazy column is clicked i need to expand the state of that item also i need to collapse the item which is already expanded, I'm not able understand how to collapse already expanded item. Please help
    s
    • 2
    • 1
  • n

    Nacho Ruiz Martin

    07/24/2021, 5:43 PM
    Hey! 👋 Anyone tried to use ConstraintLayout + Chains + margins? I don’t get why this isn’t working as expected (group is vertically centred but there are margins between fields and button).
    t
    • 2
    • 2
  • r

    RE

    07/24/2021, 5:54 PM
    I don't know if this is a BUG or deliberately. When the horizontal arrangement of Row is set to "END", Compose still measures the layout from left to right.
    t
    a
    • 3
    • 12
  • k

    kevindmoore

    07/24/2021, 7:13 PM
    Probably a dumb question, but why is compose so tied to a particular kotlin version? I need 1.5.21 for desktop compose but jetpack compose seems to need 1.5.10
    a
    • 2
    • 1
  • c

    Colton Idle

    07/25/2021, 1:30 AM
    Code review request! Please be nice as compose + navigation makes my brain hurt. Project = login/logout screens + compose + AAC compose nav + Hilt + AAC ViewModel These ~100 lines of code will serve as the base of my project. Appreciate any input you may have. https://github.com/ColtonIdle/ComposeSignInSample/blob/main/app/src/main/java/com/example/composesigninsample/MainActivity.kt
    b
    a
    a
    • 4
    • 30
  • a

    Adib Faramarzi

    07/25/2021, 5:24 AM
    Is there a way to get notified of user’s press on back button? There used to be a
    LocalBackDispatcher
    which does not seem to be there anymore.
    s
    • 2
    • 2
  • a

    Abhishek Dewan

    07/25/2021, 7:50 AM
    Does anyone have a good way to create a vertical divider ? I have
    Box(
            modifier = Modifier
                .width(1.dp)
                .fillMaxHeight()
                .background(ScoutTheme.colors.dividerColor.copy(alpha = 0.12f))
        )
    but I am seeing that when it's used inside a Row who's height is dynamic, nothing ever renders. If I replace the fillMaxHeight with a specific height I see it render but then I have the potential to get empty spaces since the height is specific rather than being dynamic
    t
    a
    m
    • 4
    • 4
  • n

    Nacho Ruiz Martin

    07/25/2021, 10:49 AM
    👋 Is there a better way to "inherit" from a Composable than redeclaring all the parameters of the inherited? I want to extend the functionality of some Material composables with custom logic that I don't want to repeat everywhere.
    c
    c
    +2
    • 5
    • 15
  • u

    ursus

    07/25/2021, 2:21 PM
    are there plans for compose testing to be on jvm? emulator are a pain to setup on ci/cd and most use cloud providers who don't allow you virtualization so it takes for ever or should I try harder to make emulators work with stupid gitlab
    t
    • 2
    • 2
  • m

    mario

    07/25/2021, 3:09 PM
    Is there a way to view the icons of material icons library on the IDE or some website?
    a
    • 2
    • 1
  • k

    kevindmoore

    07/25/2021, 3:18 PM
    I’m getting this error message (which is strange as I am using that version of Kotlin): “this version (1.0.0-rc01) of the Compose Compiler requires Kotlin version 1.5.10 but you appear to be using Kotlin version 1.4.31 which is not known to be compatible.”
    m
    u
    • 3
    • 4
  • m

    ms

    07/25/2021, 4:17 PM
    When using
    ModalBottomSheetLayout
    , is there any way to disable
    isHalfExpandedEnabled
    'cause I want my bottom sheet to expand to it's content height
    d
    • 2
    • 3
  • m

    Mehdi Haghgoo

    07/25/2021, 5:11 PM
    How can I show snack bars above a modal drawer? Currently, the drawer hides the snack bar invoked from the drawer.
    m
    b
    • 3
    • 2
  • j

    Joey

    07/25/2021, 6:28 PM
    On compose desktop (0.4.0), once I put a LazyColumn into a BackdropScaffold (doesn't matter if its the foreground or background layer content), scrolling isn't working. I assume because the BackdropScaffold "hijacks" scroll. Is there any way to get nested scrolling working in a BackdropScaffold on Desktop? Same also applies when using for example a column with verticalScroll modifier
    t
    • 2
    • 3
  • j

    John Ugwuadi

    07/25/2021, 7:00 PM
    When using a fling gesture the scroll sometimes stops short. Is this being tracked already? Has anyone else encountered this?
    fling_bug.mp4
    ➕ 3
    a
    • 2
    • 2
  • c

    Colton Idle

    07/26/2021, 1:28 AM
    Is there a "better" way to make sure that all of my screens (looks like my app will likely have over 50+ screens) all handle the case where a user is signed in or out? example: I only have 4 screens so far (signin, home, account, settings), but I've caught myself doing this same exact pattern 3 times now. Replace
    Screen1
    with
    Screen2
    and
    Screen3
    to get an idea for my duplicated code
    @Composable
    fun Screen1Screen(navController: NavController, viewModel: Screen1ViewModel = hiltViewModel()) {
        if (viewModel.userManagerService.loggedIn) {
            ActualScreen1()
        } else {
            navController.navigate(Screen.SignInScreen.route)
        }
    }
    Making sure that most screens follow the above pattern seems super error prone.
    ❤️ 1
    a
    d
    n
    • 4
    • 50
Powered by Linen
Title
c

Colton Idle

07/26/2021, 1:28 AM
Is there a "better" way to make sure that all of my screens (looks like my app will likely have over 50+ screens) all handle the case where a user is signed in or out? example: I only have 4 screens so far (signin, home, account, settings), but I've caught myself doing this same exact pattern 3 times now. Replace
Screen1
with
Screen2
and
Screen3
to get an idea for my duplicated code
@Composable
fun Screen1Screen(navController: NavController, viewModel: Screen1ViewModel = hiltViewModel()) {
    if (viewModel.userManagerService.loggedIn) {
        ActualScreen1()
    } else {
        navController.navigate(Screen.SignInScreen.route)
    }
}
Making sure that most screens follow the above pattern seems super error prone.
❤️ 1
a

Adam Powell

07/26/2021, 1:38 AM
1. avoid calling
navigate
in composables. Navigate is not idempotent. In general be suspicious of any verbs invoked on any objects that outlive the current recomposition unless those methods are specifically designed to be composition-safe. (e.g. they only mutate snapshot state.) Use the
*Effect
APIs to create actors in the composition that can take action if present after composition is successful. 2. You can declare your own extensions on
NavGraphBuilder
that wrap the content of a destination in some navigation preamble if you like, or simply create something like a
SignedInContent
composable that accepts a
content: @Composable () -> Unit
c

Colton Idle

07/26/2021, 1:49 AM
avoid calling 
navigate
 in composables
😭. Jeez I suck at this navigation thing. lol. If only it wasn't mission critical to my every app.
or simply create something like a 
SignedInContent
 composable that accepts a 
content: @Composable () -> Unit
Ohh. That makes sense to me at least. Let me try that. That should also prevent the fact that someone could add a screen to the NavHost without thinking about whether it should behave like 99% of screens which require being SignedIn.
a

Adam Powell

07/26/2021, 1:56 AM
yeah, so once you have a
SignedInContent
you can do something like declare a
fun NavGraphBuilder.signedInComposable(..., content: ...) {
  composable(...) {
    SignedInContent(..., content)
  }
}
which then means when someone goes to add a screen they'll wonder why they're typing
composable(...
instead of
signedInComposable
like all of the other destinations in the block
➕ 1
as for mutating actions in composables, one mental model that might help is that the "pure" way to do this without a feedback loop would be to have
if (!signedIn) {
  Column {
    Text("You are logged out")
    Button(onClick = { navigator.navigate("signin") }) {
      Text("Sign in")
    }
  }
}
the sign in action is taken by the user, which mutates state, which triggers recomposition. Nothing too weird.
then you can factor that out into a lambda argument so that you don't have to know what a navigator is:
Button(onClick = onSignIn) {
(or the right destination, for that matter)
c

Colton Idle

07/26/2021, 2:02 AM
Hm. Kinda confused me on this
if (!signedIn) {
  Column {
    Text("You are logged out")
    Button(onClick = { navigator.navigate("signin") }) {
      Text("Sign in")
    }
  }
}
Breaking that apart 1.
signedIn
is a mutableStateOf() right? 2. Shouldn't the onClick mutate
signedIn
to false?
a

Adam Powell

07/26/2021, 2:03 AM
1. it's a stand-in for your condition, whatever it may be calculated from. 2. no, that state isn't owned here and that button has no right/access to mutate it.
then when you want things to happen as a side effect of something being present in the current composition, you can use the effect apis. The effect creates a sort of actor/robot that stands in for the user clicking a button. Consider the compose hello world counter:
var clicks by remember { mutableStateOf(0) }
Text("Clicked $clicks times")
Button(onClick = { clicks++ }) {
  Text("Click me")
}
but this could just as easily be:
var clicks by remember { mutableStateOf(0) }
Text("Clicked $clicks times")

// A clicker robot!
LaunchedEffect(Unit) {
  while (true) {
    delay(1_000)
    clicks++
  }
}
c

Colton Idle

07/26/2021, 2:09 AM
Oh boy. A lot of this is admittedly going over my head. Going to take some time to read through this again.
a

Adam Powell

07/26/2021, 2:11 AM
to put it another way, you shouldn't "do stuff" during composition, but you can declare the presence of a composable that will "do stuff" for you via an effect once the composition is successful.
Composition declares what is present (and by omission, absent), not things that happen at a moment in time.
You can think of this as being no different from a
Button
- it's just a button that knows how to click itself rather than waiting for a user to do it. And it doesn't have to take up space in layout or draw anything either.
c

Colton Idle

07/26/2021, 2:15 AM
Yeah. So since I've been writing a complete design system the past few months. I've gotten to know compose well, and I basically only think about drawing things in composables. I never "do" anything, but now that I have entered the world of trying to tie these things together... my brain is fried apparently.
I've been watching some of Ian Lakes videos on navigation and most recently his Q and A with Murat, but somehow I'm still missing a practical example of how this stuff ties together.
For example... the docs show this
@Composable
fun Profile(navController: NavController) {
    /*...*/
    Button(onClick = { navController.navigate("friends") }) {
        Text(text = "Navigate next")
    }
    /*...*/
}
https://developer.android.com/jetpack/compose/navigation#nav-to-composable So I thought... maybe it's okay to just do this on my "top most" screens?
a

Adam Powell

07/26/2021, 2:18 AM
the key there is that
onClick
doesn't happen during composition
👍 1
the topic of constructing feedback loops in a sound and manageable way is a hot one; I hope to spend some time with some of the others on the team (both eng and devrel) in the coming weeks helping with some guidance around it.
👀 1
c

Colton Idle

07/26/2021, 2:21 AM
Okay. I thought my
signedIn
variable which is a mutableStateOf() also falls into the category of "doesn't happen during recomposition", because I figured it wouldn't be called multiple times.
But then it sort of goes back to the point of "Well how do I do this without an onClick and with a "state" trigger" which if I'm understanding correctly is with a "LaunchedEffect" (haven't used that yet in the 3 months building a design system, hence some of my confusion here)
a

Adam Powell

07/26/2021, 2:22 AM
You can think of a
LaunchedEffect
as a kind of actor that can be present in the composition
not sure I understand the statement about the
signedIn
variable
c

Colton Idle

07/26/2021, 2:27 AM
When you said
the key there is that 
onClick
 doesn't happen during composition
I think I already "knew" that. Basically in my head. I don't want to do anything really in a composable, because I just like to pretend that it can be called 100000 times without me even realizing. I like to operate under that assumption. SOOO I thought if I had a
signedIn
mutableStateOf() then I thought even if my composable is called 10000000 times, then it would only actually execute once because
signedIn
never actually changes.
Basically saying that I understand that composables can trigger at any time, but I thought having something that uses snapshot state would only cause it to compose once, hence I thought it was safe to throw in a navigate call. Which was the wrong assumption.
a

Adam Powell

07/26/2021, 2:28 AM
ah
yeah the skip/restart machinery compose uses is at the whole-function level. If the function recomposes for any reason, the whole thing runs.
c

Colton Idle

07/26/2021, 2:30 AM
Interesting. So if the composable recomposes 1000 times... then technically navigate would have been called 1000 times?
a

Adam Powell

07/26/2021, 2:30 AM
and skip/restart is an optimization; there are plenty of cases where it won't skip.
🤯 1
Yes. You would have quite the back stack accumulated. 🙂
or to put it another way: you want to plan for skipping and locally restarting for performance, not for correctness.
💯 1
c

Colton Idle

07/26/2021, 2:31 AM
Gotcha. Okay. So that was something I wasn't understanding. Cool. So I shouldn't "bank" on optimization to prevent my method being called. Okay. This is starting to make sense. I see where my understanding was failing me.
a

Adam Powell

07/26/2021, 2:33 AM
I'd have to double check with Jeremy and Ian but there's probably a clever way of writing a harness around the
NavHost
composable call to handle login states without a trampoline, but we'd have to work through all of the potentially complicated cases.
c

Colton Idle

07/26/2021, 2:35 AM
Yeah, it's so weird, because I think of the fact that a
userIsLoggedIn
as state, and was originally thinking that this means that I could probably just handle this on the activity level. i.e. Observe if userIsLoggedIn and then navigate based on that.
a

Adam Powell

07/26/2021, 2:37 AM
you could do that too
there are a lot of ways to approach this depending on how you want the actual app to behave
c

Colton Idle

07/26/2021, 2:38 AM
Yeah. I'm trying to go "by the book" with whatever Ian suggests. He seemed to suggest that the navigation should be done on a per screen basis. https://kotlinlang.slack.com/archives/CJLTWPH7S/p1626787985077800?thread_ts=1626726997.043700&amp;cid=CJLTWPH7S
a

Adam Powell

07/26/2021, 2:43 AM
yep, Ian's spent more time with the UX teams around navigation more recently than I have 🙂
👍 1
d

dimsuz

07/26/2021, 5:25 PM
I'm lazily working on "yet another" navigation library, my main inspiration is that I want to make it declarative in the sense that you only specify your nav graph and then you never have to call 'push/pop/popTo' or whatever imperative commands. I want to make it so that backstack modification command (push/pop/popTo) will be automatically derived from the navgraph structure. What you do instead is you only say something like "navigateTo(someGraphNode)" and its place in the node hierarchy determines whether it'll be push or pop or reset or whatever.
a

Adam Powell

07/26/2021, 8:50 PM
@dimsuz in such a system how do you represent navigating to a related item on an item detail page?
it sounds like you're describing jumping between tree/graph nodes with no back stack at all
☝️ 1
d

dimsuz

07/26/2021, 11:27 PM
Backstack is being built based on fixed rules. There are two kind of nodes: Flows and Screens. Flows contain Screens (leaf nodes). Jump between two screen nodes which have the same parent is a Push unless this node is already in the recorded backstack, then it's a Pop. So in your example it would be either Push or a Pop depending on the situation. That's one of the rules, there are a few more. Node transitions are based on Hoare's hierarchical state machines, but backstack building rules are something I've invented on top of that. I'm planning to apply this for large-ish apps, to see how it'll play out. So far it does for some small experiments, I'll have to do a lot more.
a

Adam Powell

07/27/2021, 12:29 AM
do report back, sounds interesting 🙂
➕ 1
👌 1
n

Nick

01/06/2022, 6:00 PM
I’m questioning my authentication flow based on your guy’s conversation. In our app, you have to be authenticated to view any content.
@Composable
fun NavGraph() {
    val navController = rememberNavController()

    val authenticationState =
        viewModel<SignInViewModel>().authenticationState.collectAsState(initial = Unknown).value
    when (authenticationState) {
        is Authenticated -> {
            NavHost(navController = navController, startDestination = NavRoots.ProjectRoot.route) {
                projectNavigation(navController)
            }
        }
        is Unauthenticated -> {
            NavHost(navController = navController, startDestination = NavRoots.AuthRoot.route) {
                authenticationNavigation(navController)
            }
        }
        is Unknown -> Text(text = "Loading")
        else -> Text(text = "else $authenticationState")
    }
}

fun NavGraphBuilder.projectNavigation(navController: NavHostController) {
    navigation(
        startDestination = ProjectRoutes.ProjectList.route,
        route = NavRoots.ProjectRoot.route
    ) {

        composable(ProjectRoutes.ProjectList.route) {
            ProjectsScreen(navController)
        }
}
When I switch the
navHost
via the result from the viewmodel, it’ll call
navigate
under the hood, correct? So this would violate the first point that Adam made in his first message right?
a

Adam Powell

01/06/2022, 6:25 PM
I'd need to read some navigation-compose code to be sure but I think using the same navController there could go sideways. The idea I've been working with is that the unauthenticated path has its own navController instance, and that unauthenticated branch is emitted per-destination on the authenticated path
n

Nick

01/06/2022, 6:55 PM
ahh yeah, it seems to be working fine for us now with the same navController. In terms of what you said in #1, would the code I put above run into any issues with recomposition? Should I put this in an effect?
c

Colton Idle

01/06/2022, 7:40 PM
I think that looks fine? I know @Ian Lake has chimed in on this sort of thing a lot in the past, and basically has said that you should try to shape it so that you check the auth in each screen and handle it from their. In my mind, that's a lot of duplicate code and it leaves room for error if you business requires "In our app, you have to be authenticated to view any content." But.... to Ians point. If your product team ever comes back and say "Hey. pretty please. can you make this one screen handle an un-auth user AND an auth user" then you're sort of screwed and you have to do all this checking anyway. A good example he gave is twitter. You typically are hit with a login screen if you go to twitter.com, but if you get a link to a specific URL, twitter does allow you to view the tweet itself.
❤️ 1
a

Adam Powell

01/06/2022, 9:05 PM
my preference for the implementation details of, "check the auth in each screen and handle it from there" is to selectively emit either the logged in content or the login flow rather than doing trampoline nav, but essentially yes. You can wrap it up into something like
loggedInComposable
in your
NavHost
block and it's really no more cumbersome
❤️ 1
d

dimsuz

01/07/2022, 5:13 PM
We have built an abstraction on top of NavHost/NavController which simply uses them as a "driver" to push/pop screens. And instances of this abstraction (NavFlow) contain logic which decides which screens to push, which dependencies to supply to those screens (auth or no-auth) etc. These flows are composable, i.e. provide means to start another flow when one finishes etc. So NavController is basically an implementation detail, this "driver" code knows nothing about authentication.
View count: 2