简体   繁体   中英

Listen for variable changes

Can I somehow create a listener (that is not a button) that listens for a variable change (in the application scope), and when the change occur, execute some code?

If that is possible, can someone give me an example of how this is done the best way?

If you need more context to answer the question (code etc..) I can provide it. But right now I just want to get a general understanding of this.

You can make the variable private, and create a setter for it. And call your listener method inside the setter after changing variable

Here is a quite awesome example

public class InformationVo extends SimpleObservable<InformationVo> {

    private String name;
    private String urls;

    public String getName() {
        return name;
    }

    public void setUrls(String urls) {
        this.urls = urls;
        notifyObservers(this);
    }

    public int getUrls() {
        return urls;
    }

    public void setName(String name) {
        this.name = name;
        notifyObservers(this);
    }
}

Here is the observer class that you want

public class SimpleObservable<T> implements EasyObservable<T> {

    private final ArrayList<OnChangeListener<T>> listeners = new ArrayList<OnChangeListener<T>>();


    public void addListener(OnChangeListener<T> listener) {
        synchronized (listeners) {
            listeners.add(listener);
        }
    }

    public void removeListener(OnChangeListener<T> listener) {
        synchronized (listeners) {
            listeners.remove(listener);
        }
    }

    protected void notifyObservers(final T model) {
        synchronized (listeners) {
            for (OnChangeListener<T> listener : listeners) {
                listener.onChange(model);
            }
        }
    }

Hope it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM