Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I notify a class component of an event?

I have class named A and its component class called B.

public class A {
    B myB;

    ...
    public void bWasUpdated(){
       ...
        List<String> list = myB.connections;
    }
}

If I have an instance of B in my class A and if that instance of B gets updated somehow, how can I notify my instance of class A and call bWasUpdated()?

I tried interfaces but ended up really confused. I guess I don't quite understand how to pass data yet between an object and its component.

EDIT

public class B {
    ArrayList<String> connections;

    ....

    public void listen(){

        ...
        if(foundNewConnection){
            this.connections.add(theNewConnection);
            //Notify class A about this new connection;
        }
    }
}
like image 341
waylonion Avatar asked Feb 19 '16 04:02

waylonion


2 Answers

You should use a Listener, which is a form of the pattern called the Observer pattern.

First, add this interface to your B class:

public interface ChangeListener {
    public void onChangeHappened();
}

Second, add a listener variable to B with a setter:

private ChangeListener listener;

public void setChangeListener(ChangeListener listener) {
    this.listener = listener;
}

Third, make A implement the ChangeListener interface and register itself as a listener:

public class A implements ChangeListener {

public A() {
    myB = new B();
    myB.setChangeListener(this);
}

...

public void onChangeHappened() {
    // do something with B now that you know it has changed.
}

And last but not least, call your listener inside B when something changes:

public void someMethodInB() {
    // change happened
    if (listener != null) {
        listener.onChangeHappened();
    }
}
like image 67
FlyingPumba Avatar answered Sep 21 '22 18:09

FlyingPumba


if B - inner class of A, then you can invoke in B setters (or other state-modifiers) A.this.bWasUpdated();

like image 21
waxtah Avatar answered Sep 21 '22 18:09

waxtah