package be.iminds.ilabt.jfed.util;

import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.ReadOnlyObjectProperty;

/**
 * User: twalcari
 * Date: 7/2/2014
 * Time: 14:14
 */
public abstract class ExecuteOnNotNull<T> implements Runnable {
    private final ReadOnlyObjectProperty<T> objectProperty;

    public ExecuteOnNotNull(final ReadOnlyObjectProperty<T> objectProperty) {
        this.objectProperty = objectProperty;

        if (objectProperty.get() != null) {
            run();
        } else {
            objectProperty.addListener(new InvalidationListener() {
                @Override
                public void invalidated(Observable observable) {
                    if (objectProperty.get() != null) {
                        run();
                        objectProperty.removeListener(this);
                    }
                }
            });
        }
    }
}
