Search code examples
androidmvvmandroid-databindingandroid-livedata

Fragment lose data from ViewModel after recreating view


Imagine that you have 2 fragments connected to one (or more) viewModel(s) and inside of activity you'll switch between them. Once you open fragment, viewModel works as expected, so I start listening for changes from onCreate method, code example:

 viewModel =  new ViewModelProvider(requireActivity(), new InventoryTasksFactory()).get(InventoryTasksViewModel.class);
    viewModel.inventoryTasksResponse().observe(this, new Observer<Response<List<InventoryTask>>>() {
        @Override
        public void onChanged(Response<List<InventoryTask>> listResponse) {
            handleResponse(listResponse);
        }
    });

But when you switching to another fragment and going back, fragment becomes blank. I understand that fragment listening changes inside of viewModel, and you should manually getting value from viewModel and I get value from viewModel inside of onCreateView method, code example:

 Response<List<InventoryTask>> inventory = viewModel.inventoryTasksResponse().getValue();
    if (inventory!=null){
        handleResponse(inventory);
    }

Problem is that Response has 3 states: Running, Success, Error, and depends on those states view is updating. So, in first fragment opening, view updating twice and it leads to skipping frames and display blinking.

I was thinking about keeping data inside of fragment, but I want to avoid data duplicating. Besides of that, in case of sharedViewModel, you'll get issues about updating data inside of fragment!

Please, help me!


Solution

  • Observing your data from onViewCreated(View view, Bundle savedInstanceState) might work out.