Search code examples
androidandroid-lifecyclecountdowntimerandroid-viewmodel

CountDownTimer : In Activity, ViewModel or separate class?


I would like to create a CountdownTimer which will trigger events that will update the UI (trigger popup, start an animation, etc.).

I wonder how to do this clean, here are my hypothesis and why :

  1. A separate component EventCountdownTimer. I could then benefit the use of LifecycleObserver, but I wonder how to communicate the information back to the activity (I tried extending CountdownTimer and using it in the activity but I have an error and can't get it to compile)
  2. In the Activity itself, it's the simplest but I'm not sure it belongs there as it isn't a UI component and I can't benefit the LifecycleObserver
  3. In the ViewModel. I thought as it's activity related and the CountdownTimer is kinda logic data, it should go in here, but that means also watching the lifecycle of the activity, and holding any Activity related field within ViewModel is bad practice.

What's the best option according to you? And why?


Solution

  • A separate component "EventCountdownTimer"

    In my opinion, this is the best implementation that you might have in your case. For communicating information back to your activity, you might consider having an interface like the following.

    public interface TimerListener {
        void onTimerResponse(String response);
    }
    

    Modify your EventCountdownTimer to have a constructor which takes TimerListener as a parameter and override the onTimerResponse method in your activity. Now from your EventCountdownTimer, when you are trying to communicate with your activity along with a message, for example, you might just call the function onTimerResponse(msgToDeliver).

    Hence your EventCountdownTimer should look something like this.

    public class EventCountdownTimer {
        public static Context context;
        public static TimerListener listener;
    
        public EventCountdownTimer(Context context, TimerListener listener) {
            this.context = context;
            this.listener = listener;
        }
    
        public startCountdown() {
            // Start the count down here
            // ... Other code
    
            // When its time to post some update to your activity
            listener.onTimerResponse(msgToDeliver);
        }
    }
    

    And from your activity, initialize the EventCountdownTimer like the following.

    EventCountdownTimer timer = new EventCountdownTimer(this, new TimerListener() {
        @Override
        public void onTimerResponse(String message) {
            // Do something with the message data 
            // Update your UI maybe
        }
    });
    

    I think you have provided good reasons already for not going for other options that you have mentioned.