Is there a "better" way to make sure that all of m...
# compose
c
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
Copy 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
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
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
yeah, so once you have a
SignedInContent
you can do something like declare a
Copy code
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
Copy code
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:
Copy code
Button(onClick = onSignIn) {
(or the right destination, for that matter)
c
Hm. Kinda confused me on this
Copy code
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
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:
Copy code
var clicks by remember { mutableStateOf(0) }
Text("Clicked $clicks times")
Button(onClick = { clicks++ }) {
  Text("Click me")
}
but this could just as easily be:
Copy code
var clicks by remember { mutableStateOf(0) }
Text("Clicked $clicks times")

// A clicker robot!
LaunchedEffect(Unit) {
  while (true) {
    delay(1_000)
    clicks++
  }
}
c
Oh boy. A lot of this is admittedly going over my head. Going to take some time to read through this again.
a
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
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
Copy code
@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
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
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
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
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
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
Interesting. So if the composable recomposes 1000 times... then technically navigate would have been called 1000 times?
a
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
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
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
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
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
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&cid=CJLTWPH7S
a
yep, Ian's spent more time with the UX teams around navigation more recently than I have 🙂
👍 1
d
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
@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
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
do report back, sounds interesting 🙂
1
👌 1
n
I’m questioning my authentication flow based on your guy’s conversation. In our app, you have to be authenticated to view any content.
Copy code
@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
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
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
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
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
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.