ObservableLazyListField.java

package ui.common.properties;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.util.List;
import java.util.function.Supplier;

import static javafx.beans.binding.Bindings.bindContent;

/**
 * Lazy initialized observable list. Changes to the observable list are updated
 * in the original list, automatically. The original list must not be changed
 * directly anymore or unexpected results could occur.
 *
 * @param <O> list element class
 * @author ken
 */
public class ObservableLazyListField<O> extends LazyListField<O> {

    private ObservableList<O> observableList;

    @Override
    public final ObservableList<O> get(Supplier<List<O>> initialValueSupplier) {
        super.get(initialValueSupplier);
        if (observableList == null) {
            observableList = FXCollections.observableArrayList(list);
            bindContent(list, observableList);
        }
        return observableList;
    }

}