Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a listener in Java?

Tags:

java

listener

I looked for this online, but couldn't find an adequate explanation to what it exactly does. What I saw was a Java Interface and it was passed as a parameter in another class as a "Listener". People added various listeners to a list and called them all through a single method.

I'm not sure why I would use it. Can someone care to explain?

This is my original help post where someone told me to use listeners.

Link

like image 537
Jacob Macallan Avatar asked Jul 25 '15 11:07

Jacob Macallan


People also ask

What is the purpose of a listener?

As a listener, your role is to understand what is being said. This may require you to reflect on what is being said and to ask questions. Reflect on what has been said by paraphrasing. "What I'm hearing is... ," and "Sounds like you are saying...

Why do we need to have a listener in an interface?

In short, a listener is useful anytime a child object wants to emit events upwards to notify a parent object and allow that object to respond.

What is event and listener in Java?

The Event listener represent the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class.

What does a listener do in event handling?

The listener is programmed to react to an input or signal by calling the event's handler. The term event listener is often specific to Java and JavaScript. In other languages, a subroutine that performs a similar function is referred to as an event handler.


2 Answers

In the code example that you linked the KillMonsterEventListener

public interface KillMonsterEventListener {
    void onKillMonster ();
}

provides a way for users of your API to tell you something like this:

Here is a piece of code. When a monster is killed, call it back. I will decide what to do.

This is a way for me to plug in my code at a specific point in your execution stream (specifically, at the point when a monster is killed). I can do something like this:

yourClass.addKillMonsterEventListener(
    new KillMonsterEventListener() {
        public onKillMonster() {
            System.out.println("A good monster is a dead monster!");
        }
    }
);

Somewhere else I could add another listener:

yourClass.addKillMonsterEventListener(
    new KillMonsterEventListener() {
        public onKillMonster() {
            monsterCount--;
        }
    }
);

When your code goes through the list of listeners on killing a monster, i.e.

for (KillMonsterEventListener listener : listeners) {
    listener.onKillMonster()
}

both my code snippets (i.e. the monsterCount-- and the printout) get executed. The nice thing about it is that your code is completely decoupled from mine: it has no idea what I am printing, what variable I am decrementing, and so on.

like image 75
Sergey Kalinichenko Avatar answered Nov 15 '22 14:11

Sergey Kalinichenko


Listener is a common form of implementing the observer design patter in Java. This technique is also referred to as the callback, which is a term coming from the world of procedural languages.

Observers register themselves by the observable, which in turn calls back the observers whenever some event occurs or when they should be notified about something.

Many framework libraries play the role of the observable, e.g.:

  • You register yourself (i.e., your implementation of the listener interface) as a listener of incoming messages in a messaging middleware.
  • You register yourself as a listener of some changes made by the user in the operating system.
  • You register yourself as a listener of GUI events, such as a button was click on.

Example in Java code:

Part 1 - The observable entity

import java.util.LinkedList;
import java.util.List;

public class Observable {
    private List<Observer> observers;

    public Observable() {
        observers = new LinkedList<>();
    }

    public void addObsever(Observer observer) {
        observers.add(observer);
    }

    private  void notifyObservers(String whatHappened) {
        for (Observer observer : observers) {
            observer.onSomethingHappened(whatHappened);
        }
    }

    public void doSomeStuff() {
        // ...
        // Do some business logic here.
        // ...

        // Now we want to notify all the listeners about something.
        notifyObservers("We found it!");

        // ...
        // Do some business logic here
        // ...
    }
}

Part 2 - The observer/listener interface

public interface Observer {
    void onSomethingHappened(String whatHappened);
}

Part 3 - Basic implementation of the observer/listener interface

public class MyObserver implements Observer {
    @Override
    public void onSomethingHappened(String whatHappened) {
        System.out.println(whatHappened);
    }
}

Part 4 - Putting it all together

public class Main {
    public static void main(String[] args) {

        // Create the observable.
        Observable myObservable = new Observable();

        // Create the observers (aka listeners).
        Observer myObserverA = new MyObserver();
        Observer myObserverB = new MyObserver();

        // Register the observers (aka listeners).
        myObservable.addObsever(myObserverA);
        myObservable.addObsever(myObserverB);

        myObservable.doSomeStuff();

    }
} 

And the result on standard output will be:

We found it!
We found it!
like image 30
MartinCz Avatar answered Nov 15 '22 15:11

MartinCz