切换片段后,ViewModel无法更新

时间:2019-05-09 05:40:50

标签: android mvvm bottomnavigationview

让我们假设底部导航栏有两个片段,即HOME和CART。在CART片段中,已显示项目列表(比方说5个项目),用户可以从中删除任何项目。如果用户通过使用“发布/删除” Web请求删除了2个项目,则该项目按预期运行,并且回复并更新了一个新列表。一切都很好,直到这里。该购物车已按预期更新,此时包含3个项目。现在,如果用户切换到HOME片段并按回CART片段,它将显示5项,如开始所示。这是什么问题,为什么ViewModel从HOME片段返回后却没有得到更新,而从CART首先得到了更新?

截至目前,我尚未使用存储库模式,并且不包含我的方案中不需要的Room数据库。只需向Web请求发送新数据并进行相应的更新即可。

下面是我正在使用的片段和ViewModel代码。

 public class MyCart extends DashBoardFragment implements UpdateItemListener {

    View view;
    private CartViewModel cartViewModel;
    Cart_Adapter adapter;
    List<Detail> adapterList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public MyCart() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.cart_screen, container, false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Timber.e("%s onResume called", TAG);
        unbinder = ButterKnife.bind(this, view);
        cartViewModel = ViewModelProviders.of(getActivity()).get(CartViewModel.class);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new Cart_Adapter(adapterList);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);

        mActivity.showLoading();
        cartViewModel.getCart().observe(this, new Observer<ResponseWrapper<Cart>>() {
            @Override
            public void onChanged(ResponseWrapper<Cart> carts) {
                Timber.e("getCart onChanged Called");
                mActivity.hideLoading();
                if (carts.getErrorString() != null) {
                    mActivity.showErrorDialog(carts.getErrorString());
                } else {
                    Cart cart = carts.getResponse();
                    if (cart.getData().getDetail().size() > 0) {
                       mActivity.setCartBadge(cart.getData().getDetail().size());
                        adapterList.addAll(cart.getData().getDetail()); // Adding Cart Items
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    @Override
    public void onItemDelete(int position) {
        mActivity.showLoading();

        cartViewModel.deleteCartItem(adapterList.get(position).getSkuId()).observe(this, new Observer<ResponseWrapper<Cart>>() {
            @Override
            public void onChanged(ResponseWrapper<Cart> carts) {
                Timber.e("deleteCartItem onChanged Called");
                if (carts.getErrorString() != null) {
                    mActivity.hideLoading();
                    mActivity.showErrorDialog(carts.getErrorString());
                } else {
                    mActivity.hideLoading();
                    if (carts.getResponse().getData().getDetail().size() > 0) {
                        adapterList.clear();
                        mActivity.setCartBadge(carts.getResponse().getData().getDetail().size());
                        adapterList.addAll(carts.getResponse().getData().getDetail()); 
                        adapter.notifyDataSetChanged();

                    }
                }
            }
        });
    }
}

    public class CartViewModel extends AndroidViewModel {
    private static final String TAG = "CartViewModel";
    private MutableLiveData<ResponseWrapper<Cart>> cartList;
    private MutableLiveData<ResponseWrapper<Cart>> deleteFromCartList;

    public CartViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<ResponseWrapper<Cart>> getCart() {
        if (cartList == null) {
            cartList = new MutableLiveData<>();
            loadCartItems();
        }
        return cartList;
    }

    private void loadCartItems() {

        Call<Cart> call = bearerApiInterface.getCartItems();
        call.enqueue(new Callback<Cart>() {
            @Override
            public void onResponse(Call<Cart> call, Response<Cart> response) {
                if (response.isSuccessful()) {
                    cartList.setValue(new ResponseWrapper(response.body()));
                } else try {
                    String errorMessage = new APIError().extractMessage(new JSONObject(response.errorBody() != null ? response.errorBody().string().trim() : null));
                    cartList.setValue(new ResponseWrapper(true, errorMessage));
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<Cart> call, Throwable t) {
                cartList.setValue(new ResponseWrapper(true, t.getMessage()));
            }
        });
    }

    public LiveData<ResponseWrapper<Cart>> deleteCartItem(int productId) {
        if (deleteFromCartList == null) {
            deleteFromCartList = new MutableLiveData<>();
            deleteThisItem(productId);
        }
        return deleteFromCartList;
    }

    private void deleteThisItem(int productId) {
        Call<Cart> call = bearerApiInterface.deleteItemFromCart(productId);
        call.enqueue(new Callback<Cart>() {
            @Override
            public void onResponse(Call<Cart> call, Response<Cart> response) {
                if (response.isSuccessful()) {
                    deleteFromCartList.setValue(new ResponseWrapper(response.body()));
                } else try {
                    String errorMessage = new APIError().extractMessage(new JSONObject(response.errorBody() != null ? response.errorBody().string().trim() : null));
                    deleteFromCartList.setValue(new ResponseWrapper(true, errorMessage));
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<Cart> call, Throwable t) {
                deleteFromCartList.setValue(new ResponseWrapper(true, t.getMessage()));
            }
        });
    }
}

0 个答案:

没有答案