I am using EventBus to post the result to a fragment when an http request is made successfully. This works nice when there's a one subscriber and one publisher relation.
However, in my application I have a screen that uses a ViewPager
with tabs. And because the pages are very similar, I use the same fragment with a different parameter corresponding to each tab, to download data.
The Fragment looks something along these lines:
public class MyFragment extends Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
public void onEvent(ServerResponse response) {
updateUi(response);
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
And you might guess already what happens when data is received.
Since the are many subscribers with the same signature, waiting a ServerResponse
, the responses don't go to the corresponding tab, but the same response is received and displayed in every fragment, and the data gets mixed.
Do you have any idea how to solve this?
Hei! Same problem here, but I have a solution.
The problem is that you have a lot of Fragments
(instances from same object) and all of them are listening the same event, so all of them are updated when you post an event.
When you post an event, try send a position and when you instantiate your Fragment
you need to store the page adapter position. After just check if the event has the same position of your Fragment
.
For example:
public static QuestionFragment newInstance(int position) {
QuestionFragment fragment = new QuestionFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vMain = inflater.inflate(R.layout.fragment_question, container, false);
EventBus.getDefault().post(new GetQuestionEvent(mPosition));
return vMain;
}
public void onEvent(GetQuestionEvent e) {
if (e.getQuestion().getPosition() == mPosition) {
TextView tvPostion = (TextView) vMain.findViewById(R.id.tv_position);
tvPostion.setText("" + e.getQuestion().getPosition());
}
}