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

li.rudin.rt.api.observable.Observable Maven / Gradle / Ivy

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

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

import li.rudin.rt.api.observable.base.BasicObservable;

/**
 * Observable Value
 * @author user
 *
 * @param 
 */
public class Observable implements BasicObservable
{
	
	/**
	 * Creates an observer with null value
	 */
	public Observable() {}
	
	/**
	 * Creates an observer with given default value
	 * @param value
	 */
	public Observable(T value)
	{
		set(value);
	}
	
	/**
	 * All local listeners
	 */
	private Set> listeners = new CopyOnWriteArraySet<>();
	
	/**
	 * The current value
	 */
	private T value;
	
	@Override
	public void set(T value)
	{
		if (value != null && this.value != null && value.equals(this.value))
			//No changes
			return;
		
		T oldValue = this.value;
		this.value = value;
		
		for (Listener l: listeners)
			l.onChange(oldValue, value);
	}

	@Override
	public T get()
	{
		return value;
	}
	
	@Override
	public void addListener(Listener l)
	{
		listeners.add(l);
	}

	@Override
	public void removeListener(Listener l)
	{
		listeners.remove(l);
	}

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




© 2015 - 2025 Weber Informatics LLC | Privacy Policy