AndroidX Lifecycle on steroids (aka multiple inheritance)

Alexander Shafir
ProAndroidDev
Published in
2 min readJan 8, 2021

--

https://refactoring.guru/design-patterns/visitor

Per AndroidX Lifecycle docs:

Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments. These components help you produce better-organized, and often lighter-weight code, that is easier to maintain.

It is nice example of inheritance-over-composition approach, where you add logic to your component instead of subclassing it to just override some methods.

However, AndroidX Lifecycle is not specific towards components and has unified set of callbacks. If you need to listen to, say, specific methods of DialogFragment, you are out of luck and need to implement this yourself.

In case your are in such situation, I have written a few lines of code that may save you some time.

I give example for DialogFragment (same code goes for Fragment).

First you need to create interface for Fragment methods that we are interested in (up to your needs):

We will also create stub implementation:

Now you need to create DialogFragment that one needs to extend from.

Note: Here I used hack to obtain moment exactly after fragment constructor gets invoked. You may opt out from using it.

Now time for usage example!

We will create DialogFragment that counts how many times it was shown on screen.

On top of it we will create extension function that shows DialogFragment only in case it was not shown already.

Final usage. Note that we use Kotlin’s ability for companion object inheritance.

--

--