Search code examples
androidviewmodelandroid-architecture-components

How ViewModel state is automatically updated


In an activity, I declared a chronometer

Chronometer chronometer = findViewById(R.id.timer);

ChronometerViewModel viewModel = ViewModelProviders.of(this).get(ChronometerViewModel.class);
if (viewModel.getStartTime() == null) {
   long startTime = SystemClock.elapsedRealtime();
        viewModel.setStartTime(startTime);
        chronometer.setBase(startTime);
    } else {
        chronometer.setBase(viewModel.getStartTime());
    }
 chronometer.start();

ViewModel class

public class ChronometerViewModel extends ViewModel {
  @Nullable
  private Long mStartTime;

  @Nullable
  public Long getStartTime() {
    return mStartTime;
  }

  public void setStartTime(final long startTime) {
    this.mStartTime = startTime;
  }
}

When I rotated the screen, chronometer automatically resumes from the previous state. But I did not write any code which stores the current state of the timer to ViewModel class on configuration change. How is the state automatically restored?

I am following this google's codelabs tutorial

Edit: I was confused with the setBase method of Chronometer. I assumed that my state variable, mStartTime is automatically getting updated to current time that was showing in Chronometer widget. Now I have checked the documentation of setBase method. since mStartTime persists on confirguration change, we can use old value from which Chronometer has started. So Chronometer actually resumes.


Solution

  • ViewModel lifecycle is as below, Android introduced it for the same purpose, so that it can survive configuration changes and doesn't loose state until activity is finished

    BTW, are you facing any issue because of this behavior?

    ViewModel lifecycle