Thursday, 1 April 2021

Can I add Observer inside Observer? I actually tried but inner observers not working properly. Sometimes one of them work, sometimes no one work

I used Android Architecture Components (ViewModel, LiveData) and used Room to fetch data from Local Sqlite Database using Repository. Outermost observer just fine, problem is only with inner observers.

See the Code:

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);

        Observer<Bank> bankObserver = new Observer<Bank>() {
            @Override
            public void onChanged(Bank bank) {
                if(bank!= null)
                    binding.tvBank.setText(bank.getBank());
            }
        };


        branchDetailsViewModel.getBranchById(branchIid).observe(this, new Observer<Branch>() {
            @Override
            public void onChanged(Branch branch) {

                branchDetailsViewModel.getBankById(branch.getBankId()).observe(getViewLifecycleOwner(), bankObserver);

                branchDetailsViewModel.getCityById(branch.getCityId()).observe(requireActivity(), new Observer<City>() {
                    @Override
                    public void onChanged(City city) {
                        if(city != null)
                        binding.tvCity.setText(city.getCity() + " cty");
                    }
                });

                branchDetailsViewModel.getDistrictById(branch.getDistrictId()).observe(requireActivity(), new Observer<District>() {
                    @Override
                    public void onChanged(District district) {
                        if(district != null)
                        binding.tvDistrict.setText(district.getDistrict());
                    }
                });

                branchDetailsViewModel.getStateById(branch.getStateId()).observe(requireActivity(), new Observer<State>() {
                    @Override
                    public void onChanged(State state) {
                        if(state!= null)
                        binding.tvState.setText(state.getState());
                    }
                });
            }
        });
    }

I tried it both using named and anonymous Observers. I can't understand what is the problem here.

One more issue is that I am unsure which one I should use in Fragment as Observer's owner, requireActivity() or getActivity()(I get warning that this could return null, so I haven't used it) or getViewLifecycleOwner() (to get fragment's life cycle owner object).



from Can I add Observer inside Observer? I actually tried but inner observers not working properly. Sometimes one of them work, sometimes no one work

No comments:

Post a Comment