简体   繁体   中英

Send live data from ViewModel to Adapter of ViewPager2

I have a sharedViewModel with a live data variable that sends data to my fragments, everything goes well and I can capture the variables in the fragments. However, as recommended I get the sharedViewModel inside onViewCreated, as follows below:

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        DataInitialViewModel initial = new ViewModelProvider(requireActivity()).get(DataInitialViewModel .class);
        initial .getStatusUser().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if(ConstsSubscribe.USER_STANDARD.equals(s)){
                    if(adapter != null)
                        isAssinante = true;
                        Toast.makeText(getContext(), "test", Toast.LENGTH_SHORT).show(); // Never enter here

                }else{
                    if(adapter != null)
                        isAssinante = false;
                        Toast.makeText(getContext(), "comaefeq", Toast.LENGTH_SHORT).show(); // Never enter too...
                }
            }
        });
    }

The problem is that I fill an adapter in my onCreateView, however, that adapter is filled using Firebase data (which takes some time). So, even with the observer, my variable can never capture when the adapter is different from null, keeping it always null, I can never pass the state of my variable to my adapter. Is there any way to capture my live data inside my adapter?

adapter = new DieAdapter(root.getContext(), dieArrayListAdp, manager, isAssinante); // var isAssinante is never updated... adapter is send to ViewPager2 to setAdapter command after.

我阅读了 onCreateView 上的实时数据,工作正常,是我问题的独特解决方案,即使困难也不会更大。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM