I encountered the same issue. As @sergej shafarenka pointed out, viewpagers basically pre-loads a fragment based on your viewpager settings (which defaults to 1).
What's happening is your subscribed to the same object for each of your Fragments (i.e., VolleySuccesObject
for your case). Now, while your Fragment A is in the foreground, Fragment B also gets loaded and so does its lifecycles, which where you register your bus.
At this point Fragment A and B (assuming, you're currently at Fragment A) are both listening to VolleySuccesObject.
The solution is based on your use-case, of course. My scenario is that I send a request for a Person
object based off of an id
. Now my Fragment A and B will receive these Person A
and Person B
, but both my fragments will receive this object. The Person
object I get back doesn't give the Person's id
, so that was a big issue since I had no way to find out for which the Person object is for.
Solution:
I used a wrapper for my Person objects (PersonResponseWrapper) where my API Service responsible for returning this PersonResponseWrapper that contains both the Person
AND the id
. So when on my @Subscribe, I have this code:
private String mId; //id used for the API call
@Subscribe
public void onPersonReponseReceived(PersonResponseWrapper response) {
if(mId.equalsIgnoreCase(response.getid()) { //Yup, this the Person object for me. Processing...
process(response.getPerson());
}
}
Hope this helped. This plagued me for days! Will answer this post in case someone encounters a similar requirement.