Created
July 6, 2012 01:17
-
-
Save JakeWharton/3057437 to your computer and use it in GitHub Desktop.
Scoped event bus which automatically registers and unregisters with the lifecycle.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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.
You still need to call register on child's life cycle, since you didn't call register(this) on BaseActiivty
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
I'm assuming the lines 13 & 17 in BaseActivity the "bus" variable should be "scopedBus", right?