https://kotlinlang.org logo
#android
Title
# android
i

iex

03/24/2020, 1:54 PM
Hi! I wrote this extension to be able to handle back button event in fragments:
Copy code
fun Fragment.onBack(consume: Boolean = false, callback: () -> Unit) {
    activity?.onBackPressedDispatcher?.addCallback {
        callback()
        if (!consume) {
            findNavController().navigateUp()
        }
    }
}
Works perfectly when I don't want to consume the event. It also works when I consume it, except that after it the back button is dead. How do I consume only the current back press?
a

Adam Powell

03/24/2020, 2:23 PM
what's a, "current" back press? 🙂 You've added a callback, it will continue to listen for events until you remove it
You can use the overload of
addCallback
that accepts a
LifecycleOwner
to manage the callback automatically for you
i

iex

03/24/2020, 2:37 PM
okay, yeah I looked for methods to remove the callback but there aren't any
will try with the lifecycleowner version
a

Adam Powell

03/24/2020, 2:40 PM
the callback object itself has a
.remove()
method
you're losing the reference to it by calling the SAM-converted version of
addCallback
i

iex

03/25/2020, 1:53 PM
ah okay, will try that out when I'm back to this task 👍
thanks!
confirm that by using the
LifecycleOwner
the issues are fixed. It's weird, since I remember having tried this out but probably I was doing something else wrong then.