Colton Idle

    Colton Idle

    1 year ago
    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
    @Composable
    fun SignInScreen(
        backPressed: () -> Unit,
        viewModel: SignInScreenViewModel = hiltViewModel()
    ) {
    
    LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher.addCallback {
            backPressed()
        }
    ... //my content
    }
    then in my activity I have
    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.
    yousefa2

    yousefa2

    1 year ago
    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
    Colton Idle

    Colton Idle

    1 year ago
    Nice. Thanks for linking to the docs. I'll try this out now!
    @yousefa2 holy crap. It works! Thank you!
    yousefa2

    yousefa2

    1 year ago
    Nice! Happy to help .. just spotted a typo but I am sure you figured it out nevertheless 🙂
    Colton Idle

    Colton Idle

    1 year ago
    Oh. A typo where?
    yousefa2

    yousefa2

    1 year ago
    Just edited my original answer with a strikethrough
    Colton Idle

    Colton Idle

    1 year ago
    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
    BackHandler { onBack() }
    AWESOME
    yousefa2

    yousefa2

    1 year ago
    That makes it easy then 😄 .. nice one!