mardi 8 juin 2021

Java Listener Lambda Remove

I am wondering what may be a good way of implementing some kind of oberservable in Java without much Interface-Stuff. I thought it would be nice to use the predefined functional interfaces. For this example, I use a String Consumer to represent a listener that takes a String for notification.

class Subject {

  List<Consumer<String>> listeners = new ArrayList<>();
  
  void addListener(Consumer<String> listener) {listeners.add(listener);}

  void removeListener(Consumer<String> listener {listeners.remove(listener);}

  ...
}

class PrintListener{
  public void print(String s) { System.out.println(s); }
}

Subject subject = new ...
PrintListener printListener= new ...
subject.add(printListener); // works, i find it in the listener list
subject.remove(printListener); // does NOT work. I still find it in the list

I found the explanation:

Consumer<String> a = printListener::print;
Consumer<String> b = printListener::print;

// it holds:
// a==b       : false
// a==a       : true
// a.equals(b): false
// a.equals(a): true

So i can't use Lambdas/Function Pointers as they are.

There is always the alternative to have the good old interfaces back, s.t. we register object instances but not lambdas. But i hoped there is something more lightweight.

Aucun commentaire:

Enregistrer un commentaire