Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Created July 6, 2012 01:17
  • Star 85 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save JakeWharton/3057437 to your computer and use it in GitHub Desktop.
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
Copy link

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

@adennie
Copy link

adennie 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
Copy link

BrainKu 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
Copy link

lzou 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