Android Architecture Components: ViewModel

Image for post
Image for post

Introduction

ViewModel

Image for post
Image for post
ViewModel vs simple UI data holder

How to use ViewModel?

implementation "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
public class UsersViewModel extends ViewModel {

private List<User> userList;

public List<User> getUserList() {
if (userList == null) {
usersList = loadUsers();
}
return userList;
}

private List<User> loadUsers() {
// do something to load users
}
}
public class UsersActivity extends AppCompatActivity {

@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

UsersViewModel usersViewModel =
ViewModelProviders.of(this).get(UsersViewModel.class);

showUsers(usersViewModel.getUserList());
}
}

ViewModel vs onSaveInstanceState()

So, when should we use onSaveInstanceState()?

Flutter GDE / Android & Flutter Developer / blogger / speaker / cat owner / travel enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store