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 */publicclassLifecycleAwareTimerimplementsRunnable,DefaultLifecycleObserver {publicinterfaceOnIntervalListenerextendsLifecycleOwner {voidonTimerInterval(); }privatefinalHandler mHandler =newHandler(Looper.getMainLooper());privatefinallong mInterval;privatefinalOnIntervalListener mOnIntervalListener;publicLifecycleAwareTimer(long interval, @NonNullOnIntervalListener onIntervalListener) { mInterval = interval; mOnIntervalListener = onIntervalListener;mOnIntervalListener.getLifecycle().addObserver(this); } @Overridepublicvoidrun() {mOnIntervalListener.onTimerInterval(); } @OverridepublicvoidonResume(@NonNullLifecycleOwner owner) {mHandler.removeCallbacksAndMessages(null);mHandler.postDelayed(this, mInterval); } @OverridepublicvoidonPause(@NonNullLifecycleOwner owner) {mHandler.removeCallbacksAndMessages(null); } @OverridepublicvoidonDestroy(@NonNullLifecycleOwner owner) {mHandler.removeCallbacksAndMessages(null);mOnIntervalListener.getLifecycle().removeObserver(this); }}