How to create a lifecycle aware custom class in Android.

We all know, each component in Android has its lifecycle, be it Activity, Fragment or Service. Each component gets created and destroys (and a few other stages in between).

To create a custom class that is lifecycle aware inherently, we can use a set of libraries provided under jetpack lifecycle.

For example, I want to create a timer, which invokes a method on each interval, and also, it should be lifecycle aware so it dies with its owner.

Firstly, we will create an interface that extends LifecycleOwner, this interface is implemented all new androidx. components.

public interface OnIntervalListener extends LifecycleOwner {
    void onTimerInterval();
}

Now, we create out actual timer,

/**
 * @implNote An implementation of lifecycle aware timer, can be attached to Activity or fragment
 */
public class LifecycleAwareTimer implements Runnable, DefaultLifecycleObserver {

    public interface OnIntervalListener extends LifecycleOwner {
        void onTimerInterval();
    }

    private final Handler mHandler = new Handler(Looper.getMainLooper());

    private final long mInterval;

    private final OnIntervalListener mOnIntervalListener;

    public LifecycleAwareTimer(long interval, @NonNull OnIntervalListener onIntervalListener) {
        mInterval = interval;
        mOnIntervalListener = onIntervalListener;

        mOnIntervalListener.getLifecycle().addObserver(this);
    }

    @Override
    public void run() {
        mOnIntervalListener.onTimerInterval();
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        mHandler.removeCallbacksAndMessages(null);
        mHandler.postDelayed(this, mInterval);
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        mHandler.removeCallbacksAndMessages(null);
        mOnIntervalListener.getLifecycle().removeObserver(this);
    }
}

Now, you can use it creates a new instance from Activity or Fragment and it will die once its owner dies.