Gorks
Gorks

Reputation: 130

Saving state of Fragment on View with LiveData

Im saving the state of fragment on a View, it works in the way I expected, the problem is with the LiveData. When I navigate to other fragment and then come back to this fragment, I cant no longer observer for changes. This is the code of my OnCreateView():

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(view == null){
            view = inflater.inflate(R.layout.fragment, container, false);
            initializeViews(view);
            receivedProductViewModel.getProductMutableLiveData().observe(getViewLifecycleOwner(), new Observer<DispatchedProduct>() {
                @Override
                public void onChanged(DispatchedProduct dispatchedProduct) {
                    if(dispatchedProduct != null){
                        int index = dispatchedProducts.indexOf(dispatchedProduct);
                        dispatchedProductsAdapter.notifyItemChanged(index);
                    }
                }
            });
            btnSearch.setOnClickListener(btnSearchListener());
            btnRegister.setOnClickListener(btnRegisterListener());
            initializeRV();
        }
        return view;
    }

I'm initializing the VM in OnCreate():

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        receivedProductViewModel = new ViewModelProvider(getActivity()).get(ReceivedProductViewModel.class);
    }

Upvotes: 1

Views: 520

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 200130

Move your observe outside of your if (view == null) block. You always need to create a new Observer for your View every time onCreateView is called - the previous getViewLifecycleOwner() was destroyed when the previous onDestroyView was called, which correctly stops your previous observe callback.

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if(view == null){
        view = inflater.inflate(R.layout.fragment, container, false);
        initializeViews(view);
        btnSearch.setOnClickListener(btnSearchListener());
        btnRegister.setOnClickListener(btnRegisterListener());
        initializeRV();
    }
    receivedProductViewModel.getProductMutableLiveData().observe(
         getViewLifecycleOwner(), new Observer<DispatchedProduct>() {
            @Override
            public void onChanged(DispatchedProduct dispatchedProduct) {
                if(dispatchedProduct != null){
                    int index = dispatchedProducts.indexOf(dispatchedProduct);
                    dispatchedProductsAdapter.notifyItemChanged(index);
                }
            }
    });
    return view;
}

Upvotes: 4

Related Questions