Skip to content

Instantly share code, notes, and snippets.

@ffgiraldez
Last active August 29, 2015 14:19
Show Gist options
  • Save ffgiraldez/9290855ad266a4700553 to your computer and use it in GitHub Desktop.
Save ffgiraldez/9290855ad266a4700553 to your computer and use it in GitHub Desktop.
Dagger 2 Generic Injections
public class AccountActivity extends BaseActivity {
// ----------------------------------
// ATTRIBUTES
// ----------------------------------
private AccountComponent component;
// ----------------------------------
// LIFE CYCLE
// ----------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeComponent();
setContentView(R.layout.activity_account);
}
@Override
public void onDestroy() {
component = null;
super.onDestroy();
}
@Override
public void inject(Object toInject) {
if (!(toInject instanceof AccountFragment)) {
super.inject(toInject);
}
component.inject(cast(toInject));
}
private void initializeComponent() {
component = DaggerAccountComponent.builder()
.applicationComponent(applicationComponent())
.activityModule(activityModule())
.build();
}
}
public class AccountFragment extends BaseFragment {
// ----------------------------------
// LIFE CYCLE
// ----------------------------------
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inject(this);
}
}
public class BaseActivity extends ActionBarActivity implements Injector {
// ----------------------------------
// INTERFACES IMPL
// ----------------------------------
@Override
public void inject(Object toInject) {
Log.i(
Injector.TAG,
String.format("%s can't handle %s injection", simpleClassName(this), simpleClassName(toInject))
);
}
// ----------------------------------
// PRIVATE API
// ----------------------------------
protected ApplicationComponent applicationComponent() {
return ((MyApplication) getApplication()).component();
}
protected ActivityModule activityModule() {
return new ActivityModule(this);
}
@SuppressWarnings("unchecked")
protected <T> T cast(Object toCast) {
return (T) toCast;
}
private String simpleClassName(Object object) {
if (object == null) {
return "null";
}
return object.getClass().getSimpleName();
}
}
public class BaseFragment extends Fragment implements Injector {
// ----------------------------------
// PRIVATE API
// ----------------------------------
@Override
public void inject(Object toInject) {
((Injector)getActivity()).inject(this);
}
}
/**
* @author Fernando Franco Giráldez
*/
public interface Injector {
String TAG = Injector.class.getSimpleName();
void inject(Object toInject);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment