Lifecycle Aware Custom Class

A custom business class that can be lifecycle aware, just like ViewModel

Here is an example of timer, it can start and pause and destroy based on current lifecycle of attached Activity, Fragment or even an lifecycle aware service.

/**
 * @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);
    }
}

Last updated