0

I'm trying to use EventBus in my project and i have a problem. I have a super class for fragments with generic EVENT parameter:

public abstract class BaseNetworkFragment<EVENT extends BaseEvent> extends Fragment {

    //some code

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onApiResponse(EVENT event) {
        //some action
    }    
}

I have a super class BaseEvent. And 2 event classes:

public class EventOne extends BaseEvent{         
}

public class EventTwo extends BaseEvent{
}

I create Fragment with generic parameter EventOne and call for Api:

public class MyFragment extends BaseNetworkFragment<EventOne> {

    //some code

    //make request for Api, when ServiceHelper has results it posts EventOne
    ServiceHelper.getInstance().getSomeData();
}

Now i don't use EventTwo and everything works correctly.

But if i add im MyFragment code:

@Subscribe
public void onEventTwo(EventTwo event) {
    //some action
}

And call for Api Services, which posts EventTwo as a result, i have mistakes. My method onEventTwo(); works correctly, but method onApiResponse(); from superclass also receives EventTwo, but it can receive only EventOne! So i have ClassCastException

I also noticed, that if i remove method onApiResponse() from superclass and write it in MyFragment everything will be ok, but i need this method in superclass.

I think that problem is in generic parameter, but i can't fix it. Also i use retrofit for asynchronous requests. Please help me)

Nikita
  • 1
  • 1

1 Answers1

0

Generics and type erasure seems to be the problem.

@Subscribe
public void onApiResponse(EVENT event) {
    //some action
}

defined in your generic abstract class is really

@Subscribe
public void onApiResponse(BaseEvent event) {
    //some action
}

Due to event inheritance being true by default, posts to EventOne are also posted to its superclass BaseEvent (and onApiResponse). You can fix this disabling event inheritance in your eventbus. Assuming you're using the default eventbus, this can be done by

EventBus.builder().eventInheritance(false).installDefaultEventBus()

before the first usage of EventBus.getDefault()

JohnWowUs
  • 3,053
  • 1
  • 13
  • 20