USER'S GUIDE SOURCE CODE SAMPLES CONTACT DONATE

Easy to use implementation of observer pattern.

Observable

class Observable {
    @Subject
    Observers<Event> observers;

    public Observable() {
        MetaHelper.createObservable(this);
    }
}

Through observers you can fire an event:

observers.notify(event);

remove all observers:

observers.clear();

or both:

observers.notifyAndClear(event);

Observer

To create an Observer, put @Observe annotation on the method that accepts one parameter - Event class.

class Observer {
    private ObserverHandler handler;

    public Observer(Observable observable) {
        handler = MetaHelper.registerObserver(this, observable);
    }

    @Observe(Observable.class)
    void onEvent(Event event) {
    }
}

Note If you use an observable that extends Observable, you need to explicitly define the class of observable that fires the event: MetaHelper.registerObserver(this, observable, Observable.class);.

The handler allows you to detach Observer from Observable:

handler.unregisterAll(Observable.class);

Stop listening to a certain event:

handler.unregister(Event.class);

You can use one handler to control many Observables:

handler.add(MetaHelper.registerObserver(this, otherObservable));

And unregister all the listeners at once:

handler.unregisterAll();

MetaHelper

public static void createObservable(Object master) {
    new ObservableController<>(metasitory, master).createObservable();
}

public static ObserverHandler registerObserver(Object observer, Object observable) {
    return new ObserverController<>(metasitory, observer).registerObserver(observable);
}

public static ObserverHandler registerObserver(Object observer, Object observable, Class cls) {
    return new ObserverController<>(metasitory, observer).registerObserver(observable, cls);
}

Please, read this article if you have questions about MetaHelper.

You should also look at Event-Bus features in addition to this guide.

How it works:

User's Guide:

Androjeta

Advanced

Stable version: 2.3
Available on Java 1.7+
Android Compatible
Fork me on GitHub