I'm working in an App using the architecture MVVM, and im a little confused about how its the best way when you need to update or insert data from an event like when you click a button.
I have this in the suscribe Observers to keep track on changes, and this work well when i open the fragment after add Products to and order:
shopViewModel.getOrderWithProducts().observe(getViewLifecycleOwner(), new Observer<Resource<OrderWithProducts>>() {
@Override
public void onChanged(Resource<OrderWithProducts> pedidoResource) {
if (pedidoResource != null) {
Log.d(TAG, "onChanged: status: " + pedidoResource.status);
switch (pedidoResource.status) {
case LOADING: {
adapterPedido.displayLoading();
break;
}
case ERROR: {
adapterPedido.hideLoading();
if(pedidoResource.data != null) adapterPedido.setList(pedidoResource.data);
break;
}
case SUCCESS: {
if (pedidoResource.data != null) {
adapterPedido.hideLoading();
adapterPedido.setList(pedidoResource.data);
break;
}
}
}
}
});
}
And to update the order i do this:
public void updateOrder() {
pedidoRepository.setOrderConfirm(OrderWithProducts.getValue().data.getPedido().getId());
pedidoConProductos.getValue().data.getPedido().setConfirmado(true);
}
But i think it has to be a better way, because the Fragment doesnt automatically update the data from the Fragment. After updating this the Adapter should change.