Observer Event Model for Android/Java

The main thing that Java lacks is «observer» event model, which allows you to assign multiple listeners to an event. The following code is a simple, yet effective implementation of OEM.

package ru.d_man.extensions.events;
 
import java.lang.reflect.Method;
import java.util.ArrayList;
 
public class EventDispatcher {
 
	private int _numListeners = 0;
	private final ArrayList<Object> _listeners = new ArrayList<Object>();
	private final ArrayList<Method> _callbacks = new ArrayList<Method>();
 
	public EventDispatcher() {
 
	}
 
	public void addListener(Object scope, Method callback) {
		if (callback != null) {
			if (indexOf(scope, callback) < 0) {
				_listeners.add(scope);
				_callbacks.add(callback);
				_numListeners++;
			}
		}
	}
 
	public void removeListener(Object scope, Method callback) {
		final int index = indexOf(scope, callback);
		if (index >= 0) {
			_listeners.remove(index);
			_callbacks.remove(index);
			_numListeners--;
		}
	}
 
	private int indexOf(Object scope, Method callback) {
		for (int c = 0; c < _numListeners; c++) {
			if ((_listeners.get(c) == scope) && (_callbacks.get(c) == callback)) {
				return c;
			}
		}
		return -1;
	}
 
	public void dispatchEvent(Object target) {
		dispatchEvent(target, null);
	}
 
	public void dispatchEvent(Object target, Event event) {
		try {
			if (_numListeners > 0) {
				if (_numListeners == 1) {
					_callbacks.get(0).invoke(_listeners.get(0), target, this, event);
				} else {
					final int numListeners = _numListeners;
					final Method[] callbacks = new Method[numListeners];
					_callbacks.toArray(callbacks);
					final Object[] listeners = _listeners.toArray();
					for (int c = 0; c < numListeners; c++) {
						callbacks[c].invoke(listeners[c], target, this, event);
					}
				}
			}
		} catch (final Exception e) {
			throw(new RuntimeException(e));
		}
	}
 
	public boolean hasListener(Object scope, Method callback) {
		return indexOf(scope, callback) >= 0;
	}
}

this post is still in progress 🙂

About DevManX