Android architecture components [Part-1] — View Model

Avinash Reddy
2 min readSep 8, 2019

--

What is view model ?

View model is one of the life-cycle aware android architecture component.It is useful for persisting data on configuration changes such as screen rotations.

Why we need a view model ?

In Android, if we rotate the device(portrait to landscape and vice-versa) the activity will be recreated i.e., the activity will be destroyed(onPause->onStop->onDestroy) and recreated(onCreate->onStart->onResume).

In this process our data in the activity/fragment will be re initialized.

For example

int count = 0;

Problem :

Variable changed to 40 (for some reason in the application)→ device is rotated → Now the value will not be stored and it will reset to 0 again.

This is the problem , and where the view model will provide the solution for this.

How to use View Model ?

ViewModel class:

public class MainActivityViewModel extends ViewModel {
private int count = 0;
public void getInitialCount() {
return count;
}
public int getCurrentCount() {
count += 1;
return count;
}
}

Activity class:(Simple application where we need to keep track on number of clicks made on floating button)

public class MainActivity extends AppCompatActivity {
MainActivityViewModel mainActivityViewModel;

private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivityViewModel=
ViewModelProviders.of(this).
get(MainActivityViewModel.class);


textView=findViewById(R.id.tvCount);
textview.setText(mainActivityViewModel.getInitialCount());


FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

textview.setText
(mainActivityViewModel.getCurrentCount());

}
});
}
}

Observation points :

→View model objects are scoped to the lifecycle passed to the ViewModel provider when getting the view model.

mainActivityViewModel=ViewModelProviders.of(this).get(MainActivityViewModel.class);

→ The ViewModel remains in memory until the lifecycle it is scoped to go away permanently . Like when activity finishes , fragment detached.

→ Two fragments in an activity will share the same view model , so that they will have access to the same data.

mainActivityViewModel=ViewModelProviders.of(getActivity()).get(MainActivityViewModel.class);

Legacy methods :

Previously, before the introduction of view model api in android, the legacy method to acheive this data persistency on device rotation is using OnSavedInstance() and OnRestoreInstance() methods.

--

--