I am using a new arch. components from google.
I have Login / Register activity of fragments managed with FragmentTransaction
Activity->RegisterFragment (with ViewPager) -> RegistrationSteps (adapter)
Inside RegisterFragment I have a ViewPager. I want all the pages inside the ViewPager use the same ViewModel.
These are the registration steps ( RegistrationStepFragment ) that the parent RegistrationFragment LifecycleOwner takes, which is bound to the ViewModel to it - I just wanted the ViewModel to be bound to this parent fragment,
RegistrationFragment.class related to
public interface FragmentViewPagerListener<T extends LifecycleFragment> { void nextPage(); T getLifecycleFragment(); }
RegistartionSteps (pages) associated with
public abstract class RegisterStepFragment extends LifecycleFragment { protected FragmentViewPagerListener mListener; protected RegisterViewModel mViewModel; public void setListener(FragmentViewPagerListener fragmentViewPagerListener) { this.mListener = fragmentViewPagerListener; } protected abstract void observeViewModel(); @Override public void onCreated(@Nullable Bundle savedInstanceState) { super.onCreated(savedInstanceState); mViewModel = ViewModelProviders.of(mListener.getLifecycleFragment()).get(RegisterViewModel.class); observeViewModel(); } protected abstract boolean validateData(); }
Everything is going well until I reach 3 pages and I want to return (to the second page). Then an exception is mViewPager.setCurrentItem(1) in mViewPager.setCurrentItem(1) (p. 2: index: 1)
*java.lang.RuntimeException: Failed to call observer method at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.invokeCallback(ReflectiveGenericLifecycleObserver.java:79) at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.invokeMethodsForEvent(ReflectiveGenericLifecycleObserver.java:53) at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.invokeCallbacks(ReflectiveGenericLifecycleObserver.java:61) at android.arch.lifecycle.ReflectiveGenericLifecycleObserver.onStateChanged(ReflectiveGenericLifecycleObserver.java:45) at android.arch.lifecycle.LifecycleRegistry$ObserverWithState.sync(LifecycleRegistry.java:209) at android.arch.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.java:102) at android.arch.lifecycle.Li*fecycleDispatcher.dispatchIfLifecycleOwner(LifecycleDispatcher.java:150)
EDIT
Well, I found out that when going to the previous page, Fragment was handled by calls and mViewModel.observable() received the SUCCESS message earlier and forced the viewpager to move forward, which leads to the destruction of the just created fragment that caused an error.
The solution is to create a SingleEventLiveData that emits values ββonly when the message is called (do not notify the observer if the value is changed before the observer joins)
I mark it as CLOSE