How to get a ViewModel?

2019-06-11 11:56发布

问题:

I just want to get a reference in my Fragment (extends Fragment) to my ViewModel.class (extends from AndroidViewModel). This is how it is described everywhere:

UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);

description on Android Developer

..., but ViewModelProviders is deprecated since long ago.

*This class was deprecated in API level 1.1.0. *

I can't import the class with: android.arch.lifecycle.[ViewModelProviders]

it just offers ViewModelProvider and other stuff.


How am I able to get an instance of my UserModel.class?

回答1:

but ViewModelProviders is deprecated since long ago

ViewModelProviders is not deprecated. So, use ViewModelProviders:

ViewModelProviders.of(yourFragment).get(UserModel.class)

There are pieces of ViewModelProviders that are deprecated, such as its constructor, but the class overall is not.



回答2:

Here's how to write a ViewModel

public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
    if (users == null) {
        users = new MutableLiveData<List<User>>();
        loadUsers();
    }
    return users;
}

private void loadUsers() {
    // Do an asynchronous operation to fetch users.
}
}

And then to use it in your actctivity do something like this

public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
    // Create a ViewModel the first time the system calls an activity's onCreate() method.
    // Re-created activities receive the same MyViewModel instance created by the first activity.

    MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
    model.getUsers().observe(this, users -> {
        // update UI
    });
}
}