Akshay Veer
Akshay Veer

Reputation: 23

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.

Upvotes: 1

Views: 862

Answers (2)

Akhil
Akhil

Reputation: 6697

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

Upvotes: 1

Sergey Emeliyanov
Sergey Emeliyanov

Reputation: 6961

Your ChronometerViewModel (being a child of ViewModel) does not get destroyed with the orientation change of the Activity.

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

A ViewModel is always created in association with a scope (an fragment or an activity) and will be retained as long as the scope is alive. E.g. if it is an Activity, until it is finished.

In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just re-connected to the existing ViewModel.

I suggest you read the documentation of ViewModel: https://developer.android.com/reference/android/arch/lifecycle/ViewModel.html

Upvotes: 0

Related Questions