All Downloads are FREE. Search and download functionalities are using the official Maven repository.

li.rudin.rt.api.computed.Computed Maven / Gradle / Ivy

There is a newer version: 4.1
Show newest version
package li.rudin.rt.api.computed;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import li.rudin.rt.api.base.composite.ObservableGetter;
import li.rudin.rt.api.observable.Listener;

public class Computed implements ObservableAccessor, Listener, ObservableGetter
{
	public Computed(ComputedValue cv)
	{
		this.cv = cv;
		recompute();
	}
	
	private final ComputedValue cv;
	private T value;
	
	private boolean registerObservables = true;
	
	/**
	 * Returns the current value
	 * @return
	 */
	@Override
	public T get()
	{
		return value;
	}
	
	/**
	 */
	private void recompute()
	{
		T oldValue = value;
		
		value = cv.compute(this);
		registerObservables = false;
		
		for (Listener l: listeners)
			l.onChange(oldValue, value);
	}

	@SuppressWarnings("unchecked")
	@Override
	public  V get(ObservableGetter o)
	{
		if (registerObservables)
			o.addListener((Listener) this);
		
		return o.get();
	}

	@Override
	public void onChange(Object oldValue, Object newValue)
	{
		recompute();
	}
	
	/**
	 * All local listeners
	 */
	private Set> listeners = new CopyOnWriteArraySet<>();
	
	/**
	 * Adds a local listener
	 * @param l
	 */
	@Override
	public void addListener(Listener l)
	{
		listeners.add(l);
	}
	
	/**
	 * Removes the local listener
	 * @param l
	 */
	@Override
	public void removeListener(Listener l)
	{
		listeners.remove(l);
	}

	@Override
	public String toString()
	{
		return "Computed [cv=" + cv + ", value=" + value + ", listeners="
				+ listeners + "]";
	}
}