Using compose navigation and a single activity app...
# compose
c
Using compose navigation and a single activity app, I have a composable
SignInScreen
that should not follow the typical "back press = popBackStack". When on the SignInScreen, the MainScreen is in the stack, but in this case I want the app to just close. Where is the more appropriate place to override this? In the
SignInScreen
composable itself? Or on the activity level?
Basically this is what I had, and want to make sure I'm using the right api
Copy code
@Composable
fun SignInScreen(
    backPressed: () -> Unit,
    viewModel: SignInScreenViewModel = hiltViewModel()
) {

LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher.addCallback {
        backPressed()
    }
... //my content
}
then in my activity I have
Copy code
SignInScreen(
    { this@MainActivity.finish() },
)
A negative to this approach I've noticed is that if I have another screen I was taken to from my SignInScreen (for example, lets say ForgotPasswordScreen), then actually pressing back on ForgotPasswordScreen will actually finish the activity too. So it sounds like I'm doing something wrong. Any advice is appreciated.
y
SignInScreen is the best place but you should use DisposableEffect to register the back pressed callback when SignInScreen is displayed then re-registering de-registering the callback when it’s disposed
c
Nice. Thanks for linking to the docs. I'll try this out now!
@yousefa2 holy crap. It works! Thank you!
y
Nice! Happy to help .. just spotted a typo but I am sure you figured it out nevertheless 🙂
c
Oh. A typo where?
y
Just edited my original answer with a strikethrough
c
Ah. I got what you mean. Thanks. I thought you were saying that the docs had a typo. lol
@yousefa2 found out that you can just use this new composable added in activity-compose artifact https://developer.android.com/reference/kotlin/androidx/activity/compose/package-summary
Copy code
BackHandler { onBack() }
AWESOME
y
That makes it easy then 😄 .. nice one!
👍 1