Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scoped event bus which automatically registers and unregisters with the lifecycle.
package com.squareup.example;
public abstract BaseActivity extends SherlockActivity {
private final ScopedBus scopedBus = new ScopedBus();
protected ScopedBus getBus() {
return scopedBus;
}
@Override public void onPause() {
super.onPause();
bus.paused();
}
@Override public void onResume() {
super.onResume();
bus.resumed();
}
}
package com.squareup.example;
public class ScopedBus {
// See Otto's sample application for how BusProvider works. Any mechanism
// for getting a singleton instance will work.
private final Bus bus = BusProvider.get();
private final Set<Object> objects = new HashSet<Object>();
private boolean active;
public void register(Object obj) {
objects.add(obj);
if (active) {
bus.register(obj);
}
}
public void unregister(Object obj) {
objects.remove(obj);
if (active) {
bus.unregister(obj);
}
}
public void post(Object event) {
bus.post(event);
}
void paused() {
active = false;
for (Object obj : objects) {
bus.unregister(obj);
}
}
void resumed() {
active = true;
for (Object obj : objects) {
bus.register(obj);
}
}
}
@patjackson52

This comment has been minimized.

Copy link

commented Aug 7, 2012

I'm assuming the lines 13 & 17 in BaseActivity the "bus" variable should be "scopedBus", right?

@adennie

This comment has been minimized.

Copy link

commented Jan 25, 2013

Too bad there's not a Bus interface that ScopedBus and the existing Bus class could implement. Then code interacting with the ScopedBus could be none the wiser.

@BrainKu

This comment has been minimized.

Copy link

commented Aug 12, 2014

You still need to call register on child's life cycle, since you didn't call register(this) on BaseActiivty

@lzou

This comment has been minimized.

Copy link

commented Dec 31, 2014

BaseActivity.class there is no bus. where it come from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.