Skip to content

Instantly share code, notes, and snippets.

@hamurcuabi
Created October 29, 2022 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamurcuabi/a518a0345ad09e22927ce0aee80708e5 to your computer and use it in GitHub Desktop.
Save hamurcuabi/a518a0345ad09e22927ce0aee80708e5 to your computer and use it in GitHub Desktop.
class OnBackPressedDelegationImpl : OnBackPressedDelegation, DefaultLifecycleObserver {
private val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
onBackPressed.invoke()
}
}
private var fragmentActivity: FragmentActivity? = null
private lateinit var onBackPressed: () -> Unit
override fun registerOnBackPressedDelegation(
fragmentActivity: FragmentActivity?,
lifecycle: Lifecycle,
onBackPressed: () -> Unit
) {
this.fragmentActivity = fragmentActivity
this.onBackPressed = onBackPressed
lifecycle.addObserver(this)
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
fragmentActivity?.onBackPressedDispatcher?.addCallback(onBackPressedCallback)
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
onBackPressedCallback.remove()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment