Skip to content

Instantly share code, notes, and snippets.

@yatatsu
Last active August 29, 2015 14:26
Show Gist options
  • Save yatatsu/280dc237485c903269c2 to your computer and use it in GitHub Desktop.
Save yatatsu/280dc237485c903269c2 to your computer and use it in GitHub Desktop.
Android Flux Pattern with Otto cf. http://lgvalle.github.io/2015/08/04/flux-architecture/
/**
* Action interface
*/
public abstract class EventAction {
}
public class EventEmitter {
private static final Bus BUS = new Bus();
private EventEmitter() {}
private static class SingletonHolder {
private static final EventEmitter instance = new EventEmitter();
}
public static EventEmitter get() {
return SingletonHolder.instance;
}
public void on(Object obj) {
BUS.register(obj);
}
public void off(Object obj) {
BUS.unregister(obj);
}
public void emit(EventAction action) {
post(action);
}
/**
* Post Action in UI Thread.
*/
private void post(final EventAction action) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
BUS.post(action);
}
});
}
}
public abstract class EventStore {
private final EventEmitter eventEmitter;
protected EventStore(EventEmitter eventEmitter) {
this.eventEmitter = eventEmitter;
}
/**
* Action emitted when this store changed.
*/
protected abstract StoreChangeAction changeStoreAction();
/**
* emit self
*/
protected void emitSelf() {
eventEmitter.emit(changeStoreAction());
}
/**
* Handling Action
*/
protected abstract void onAction(EventAction action);
}
public class StoreChangeAction<T extends EventStore> implements EventAction {
private T store;
public StoreChangeAction(T store) {
this.store = store;
}
public T getStore() {
return store;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment