Hi! I wrote this extension to be able to handle ba...
# android
i
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
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
okay, yeah I looked for methods to remove the callback but there aren't any
will try with the lifecycleowner version
a
the callback object itself has a
.remove()
method
you're losing the reference to it by calling the SAM-converted version of
addCallback
i
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.