Search code examples
androidevent-busgreenrobot-eventbus

EventBus: all child classes receive event


I have BaseActivity with fun onEvent(event: MyEvent) and 4 activities that extend the BaseActivity. My problem is that BaseActivity handles all the events. That means when an event is sent, it is received by all subclasses of BaseActivity that are instantiated at the moment, which causes onEvent() to run multiple times

class BaseActivity {
    ...
    fun onEvent(event: MyEvent) {
        //do some cool stuff
    }
}

class A: BaseActivity {

}

class B: BaseActivity {

}


class SomeClass {

    fun somefun() {
        EventBus.getDefault().post(MyEvent("woadude"));
    }
}

So in this case onEvent in BaseActivity is called 2 times for each subclass.


Solution

  • If you want different messages for different objects then you need to create different structures. In your case, you want to send a message to object A and another message to object B base on some logic (which I do not know).

    My solution is to create a MyEvent inside class A, and MyEvent in class B (I know, probably is not so good as parent classes shouldn't know about children). Then your logic will be like this:

    fun somefun() {
      if("some condition"){
        EventBus.getDefault().post(A.MyEvent("woadude"));
      }if("another condition") {
        EventBus.getDefault().post(B.MyEvent("woadude"));
      }      
     }
    

    Another option is just to create different classes MyEventA and MyEventB, and each object from different classes can register to MyEventA and MyEventB respectively. With this way, you parent class does not need to know anything about children.

    Whatever solution you choose, the solution is that you need to sent different object types in order to make it work

    EDIT base on the new information you need to remove this function from BaseActivity

       fun onEvent(event: MyEvent) {
            //do some cool stuff
        }
    

    and make it abstract. Use MyEvent as the parent class of each MyEvent class for you are going to create. So you will have:

    MyEventA : MyEvent

    MyEventB: MyEvent

    then in class A you will have

    fun onEvent(event: MyEventA) {
            //do some cool stuff
        }
    

    and in class B

    fun onEvent(event: MyEventB) {
            //do some cool stuff
        }
    

    Of course, my answer could be better if you give more information about the problem.

    Hope it helps.