保持数据状态ViewModels

时间:2018-05-23 14:26:46

标签: android performance model-view-controller

因此根据android开发人员的说法:" Architecture Components为UI控制器提供了ViewModel辅助类,负责为UI准备数据。 ViewModel对象在配置更改期间自动保留,以便它们保存的数据可立即用于下一个活动或片段实例。"

在下面的代码中,有一个在deleteItem函数中调用的异步类。我的问题是:ViewModel是否也处理在其中进行的异步调用或会导致内存泄漏?

谢谢

public class BorrowedListViewModel extends AndroidViewModel {

private final LiveData<List<BorrowModel>> itemAndPersonList;

private AppDatabase appDatabase;

public BorrowedListViewModel(Application application) {
    super(application);

    appDatabase = AppDatabase.getDatabase(this.getApplication());

    itemAndPersonList = appDatabase.itemAndPersonModel().getAllBorrowedItems();
}


public LiveData<List<BorrowModel>> getItemAndPersonList() {
    return itemAndPersonList;
}

public void deleteItem(BorrowModel borrowModel) {
    new deleteAsyncTask(appDatabase).execute(borrowModel);
}

private static class deleteAsyncTask extends AsyncTask<BorrowModel, Void, Void> {

    private AppDatabase db;

    deleteAsyncTask(AppDatabase appDatabase) {
        db = appDatabase;
    }

    @Override
    protected Void doInBackground(final BorrowModel... params) {
        db.itemAndPersonModel().deleteBorrow(params[0]);
        return null;
    }

}

}

1 个答案:

答案 0 :(得分:1)

我想提供一个例子,可能你需要修改代码。 首先,您需要实时更改数据并在视图中订阅。然后在控制器中发布值,告诉订阅者附加的内容。这种方式异步,视图会收到警报。

private MutableLiveData<String> databaseLiveData = new MutableLiveData<>();

...

deleteAsyncTask课程中,您可以添加:

protected void onPostExecute(Void result) {
     databaseLiveData.postValue("some data deleted");
}

BorrowedListViewModel类中,从视图中访问此方法会添加此方法:

public LiveData<String> getChanger() {
        return databaseLiveData;
    }

在视图egActivity中添加以下内容:

 private BorrowedListViewModel mBorrowedListViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...
    BorrowedListViewModel = ViewModelProviders.of(this).get(BorrowedListViewModel.class);

    subscribe();
}

private void subscribe() {
    final Observer<String> liveDataChange = new Observer<String>() {
        @Override
        public void onChanged(@Nullable final String message) {

            Log.d("Activity", message);
        }
    };

    liveDataChange.getChanger().observe(this, liveDataChange);
}

希望得到这个帮助。