pseudo
pseudo

Reputation: 848

CDI events inheritance

Is there a way of using class inheritance with CDI Events?

Lets say I have something like this:

public class ParentEvent{}

public class ChildEvent extends ParentEvent{}

and something like this:

public class Manager(){
    @Inject 
    private Event<ParrentEvent> event;

    public void foo(){
        event.fire(new ParentEvent());
    }

    public void bar(){
        event.fire(new ChildtEvent());
    }        
}

public class Observer{

      public void observesParent(@Observes ParentEvent event){
          //do something
      }

      public void observesChild(@Observes ChildEvent event){
          //do something
      }
}

In this case both ParentEvent and ChildEvent are processed by observesParent() - due to type of event attribute in Manager class. Is there a way to observe ChildEvent with both observer methods?

Upvotes: 1

Views: 1139

Answers (1)

Jan Groth
Jan Groth

Reputation: 14636

The idea of CDI is to use qualifiers in conjunction with events / observers (and not inheritance). Check that chapter in the Weld documentation. The desired behaviour should be easily achievable with something like this:

public class Manager(){
    @Inject
    @Parent
    private Event<MyEvent> parentEvent;

    @Inject
    @Child
    private Event<MyEvent> childEvent; 

// ...

    public void foo(){
        event.fire(parentEvent);
    }

    public void bar(){
        event.fire(childEvent);
    }
}


public void observeChild(@Observes @Child MyEvent myEvent) { ... }
public void observeParent(@Observes @Parent MyEvent myEvent) { ... }
public void observeAll(@Observes MyEvent myEvent) { ... }

This far more flexible than using inheritance...

Upvotes: 2

Related Questions