-4

I have Objects that emit Strings to listeners...

The listeners extend the following class :

public abstract class StringReceiver {

    public abstract void receive(String input);

}

I don't want to reinvent the wheel. My question is : what is the appropriate class from the Java API to use for this kind of listener/receiver relationship?

Ivar
  • 6,138
  • 12
  • 49
  • 61
RealmSpy
  • 345
  • 1
  • 4
  • 12

1 Answers1

0

After much downvotes and some googling,

Thanks to Jaroslaw Pawlak, I found the answer to my question.

The answer was to completely ditch the class shown in my question and to replace it with :

List of consumers :

List<Consumer<String>> inputReceivers = new ArrayList<Consumer<String>>();

Now to add consumers :

public void addReceiver(Consumer<String> receiver) {
    inputReceivers.add(receiver);
}

And triggered on event :

    for (Consumer<String> a : inputReceivers) {
            a.accept("some string data");
    }

That's all! No need to implement any interface or extend abstract class, this works well with methods.

I can do something like this :

addReceiver(s -> { 
                if (!StringUtils.isAllBlank(s)) {
                    // deal with string s
                }
            });

Almost magic!

RealmSpy
  • 345
  • 1
  • 4
  • 12