OnBackPressed for Fragments with Delegation
The easiest way to provide ability of OnBackPressed for fragments.
The delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance. Kotlin has special support for delegation built in.
Today I am gonna write an example delegation for our fragments to handle back pressed with the easiest way. You may check my youtube video to get the details https://youtu.be/x0wvBh2Oiz0.
Let’s write a dirty code first than we will clear it with delegation pattern.
We can see there is onBackPressedCallback that we should add it to activity dispatcher callback. If we have a lots of fragment we have to copy these code or put into BaseFragment :( Here is the rescue Delegation :)
First of all we need an interface to get what we need from our fragment
Now lets create a class implements OnBackPressedDelegation
DefaultLifecycleObserver is an interface that help us to get state of lifecycles with callbacks. So how to use it in a right way ?
As you can see OnBackPressedDelegation by OnBackPressedDelegationImpl() is our delegation implementation. The by keyword is a special for delegation.
Thats it, you can reuse this code where ever you want. Don’t put all your code into the BaseFragments or God Classes :)