Skip to content

Instantly share code, notes, and snippets.

@ffgiraldez
Last active August 29, 2015 14:25
Show Gist options
  • Save ffgiraldez/f23cf667cec3fbcf1c39 to your computer and use it in GitHub Desktop.
Save ffgiraldez/f23cf667cec3fbcf1c39 to your computer and use it in GitHub Desktop.
Dagger 2 Activity Injection
/**
* @author Fernando Franco Giráldez
*/
public abstract class BaseActivity<T> extends ComponentActivity {
// ----------------------------------
// ATTRIBUTES
// ----------------------------------
private T component;
private ActivityComponent activityComponent;
@Inject
Foo foo
// ----------------------------------
// LIFE CYCLE
// ----------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityComponent = buildActivityComponent();
component = buildComponent(activityComponent);
}
@Override
public void onDestroy() {
component = null;
activityComponent = null
super.onDestroy();
}
// ----------------------------------
// INTERFACES IMPL
// ----------------------------------
protected abstract T buildComponent(ActivityComponent activityComponent);
// ----------------------------------
// PUBLIC API
// ----------------------------------
public T component() {
return component;
}
// ----------------------------------
// PRIVATE API
// ----------------------------------
private ActivityComponent buildActivityComponent() {
return DaggerActivityComponent.builder()
.applicationComponent(applicationComponent())
.activityModule(new ActivityModule(this))
.build();
}
private ApplicationComponent applicationComponent() {
return ((MyApp) getApplication()).component();
}
}
/**
* @author Fernando Franco Giráldez
*/
public class OtherActivity extends BaseActivity<OtherComponent> {
// ----------------------------------
// ATTRIBUTES
// ----------------------------------
@Inject
Bar bar;
// ----------------------------------
// LIFECYCLE
// ----------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize();
//other stuff
}
@Override
protected OtherComponent buildComponent(final ActivityComponent activityComponent) {
return DaggerOtherComponent.builder()
.activityComponent(activityComponent)
.build();
}
private void initialize() {
component().inject(this);
}
}
@cdsap
Copy link

cdsap commented Jul 21, 2015

thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment