Last week, we open-sourced LightCycle, an Android library that helps break logic out of Activity
and Fragment
classes into small, self-contained components called LightCycles.
Components that typically need to be aware of Activity
and Fragment
lifecycle events include presenters, UI tracking code, input processors and more. We’ve been using LightCycle extensively in the SoundCloud Music & Audio and SoundCloud Pulse apps over the last year.
LightCycle lets self-contained classes respond to Android’s lifecycle events. This encourages composition over inheritance and promotes components that follow the single responsibility principle. We believe it helps us write more readable, maintainable and testable code.
If this sounds familiar, RoboGuice has a similar concept called Events. However, LightCycle is a small, standalone solution that works well with all dependency injection frameworks.
public class MyActivity extends LightCycleAppCompatActivity<MyBaseActivity> {
@LightCycle MyController controller = new MyController();
@Override
protected void setActivityContentView() {
setContentView(R.layout.main);
}
}
public class MyController extends DefaultActivityLightCycle<MyActivity> {
@Override
public void onPause(MyActivity activity) {
// MyActivity was paused
}
}
The Activitiy
and Fragment
classes are responsible for configuring Android specifics and declaring LightCycles. LightCycles themselves can focus on business or presentation logic. Not being tightly coupled to the framework makes these components simpler to unit test (even without Robolectric).
The code and documentation is available on GitHub.
Acknowledgements. Huge thanks to all the contributors: Brian Egan, Fernando Cejas, Jamie McDonald, Jon Schmidt, Karolina Kafel, Matthias Käppler, Pedro Lopes.