> For the complete documentation index, see [llms.txt](https://notes.tejpratapsingh.com/android-tips/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.tejpratapsingh.com/android-tips/lifecycle/lifecycle-aware-custom-class.md).

# 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](https://developer.android.com/reference/androidx/lifecycle/LifecycleService#).

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