Below is the structure of my app
MainActivity
|-- HomeFragment
| |-- ViewPager
| |-- FirstViewFragement
| |-- SecondViewFragementme
| |-- ThirdViewFragement
|-- SettingFragment
|-- OtherFragment
The app flow is displayed below visually, if required.
Description: I have DataViewModel which allow my app to send data from MainActivity and different Fragment to another fragment or child fragment.
In my DataViewModel I have two data which which I need to send to the CanvasView (extends View) in views inside viewpager. First data is coming from MainActivity (sensor data) and another data is coming from HomeFragment (state data) to Views inside viewPager. The CanvasView < inside every < view inside < viewpager receives the data from Mainactivty and HomeFragment. These views receive the data based on which view is visible to the user. (I am just checking the current postion of viewpager and sending the position to viewmodel observer inside these CanvasView and receving the data).
Problem: When I launch the app for the first time, I receive the data on firstViewFragment but as soon as I swipe, I can no longer receive the data in the observer of these CanvasView, except the last one. Last one always receive the data no matter how many times I swipe but previous views stop receiving the data.
/* MainActivity.class*/
private FusionViewModel fusionViewModel;
dataViewModel = new ViewModelProvider(this).get(DataViewModel.class); // passing 'this' as an owner in main activity.
if(sensor.data()>0){
dataViewModel.setState(true);
}
/*CanvasView extends View*/
private FusionViewModel fusionViewModel;
dataViewModel= new ViewModelProvider((ViewModelStoreOwner) ctx).get(DataViewModel.class); // tried getContext() works as well as with ctx.
dataViewModel.getState().observe((LifecycleOwner) ctx, new Observer<Boolean>() {
@Override
public void onChanged(@Nullable Boolean bool) {
if(viewPagerPosition==0){
pressed=bool;
Log.d("STATE","Received");
}
}
});