5

我正在使用 IO/17 中引入的 ViewModel。

我正在使用 android 开发人员页面上提供的以下指南。 https://developer.android.com/topic/libraries/architecture/viewmodel.html

以下是他们的示例代码。

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

 private void loadUsers() {
    // do async operation to fetch users
 }
}

我希望在“ loadUsers() ”方法中执行 Volley 请求。但我不能这样做,因为它需要一个“上下文”,如下所示

Volley.newRequestQueue(context).add(jsonObjectRequest);

所以我的问题是,

  1. 是否建议(或可能)在 ViewModel 中执行网络操作?
  2. 如果是(如果可能),该怎么做?
4

3 回答 3

2

您可以使用 AndroidViewModel 类而不是 ViewModel。AndroidViewModel 持有对应用程序上下文的引用。

https://youtu.be/5qlIPTDE274

于 2018-06-25T02:08:12.560 回答
1

考虑Daggercontext,这样您就不必担心Volley从您的ViewModel.

于 2018-01-24T15:40:26.517 回答
1

AndroidViewModel is subclass of ViewModel. The Difference between them is we can pass Application Context which can be used whenever Application Context is required for example to instantiate Database in Repository.

AndroidViewModel is a Application context aware ViewModel.You must use AndroidViewModel for Application Context.

public class MyViewModel extends AndroidViewModel {
private MutableLiveData<List<User>> users;
private Application application;
public MyViewModel(@NonNull Application application) {
    this.application=application;
    super(application);
}
public LiveData<List<User>> getUsers() {
    if (users == null) {
        users = new MutableLiveData<List<Users>>();
        loadUsers();
    }
    return users;
}

private void loadUsers() {
    // Pass Context to Repository
}}

You should never store a reference of activity or a view that references a activity in the ViewModel.Because ViewModel is designed to outlive a activity and it will cause Memory Leak.

Is it recommended(or possible) to perform network operations inside a ViewModel??

No, you should not perform Networking Operations inside a ViewModel.

If yes(if possible), how to do it?

Get Application Context by using AndroidModelView and pass it to Repository, as recommended by Android Team.

enter image description here

于 2019-12-31T18:14:45.110 回答