Skip to content

Instantly share code, notes, and snippets.

@dotkebi
Created September 6, 2016 03:01
Show Gist options
  • Save dotkebi/6c7845d64c3b6ab2de5c0aa187db9fd0 to your computer and use it in GitHub Desktop.
Save dotkebi/6c7845d64c3b6ab2de5c0aa187db9fd0 to your computer and use it in GitHub Desktop.
Dagger2 best practices I think :)
@Singleton
@Component(
modules = {
AppModule.class
})
public interface ApplicationComponent {
void inject(MainActivity target);
final class Initializer {
private Initializer() {}
public static ApplicationComponent init(MyApplication app) {
return DaggerApplicationComponent.builder()
.appModule(new AppModule(app))
.build();
}
}
}
@Singleton
public class Dinner {
// codes...
}
public class MainActivity extends AppCompatActivity{
@Inject
Dinner dinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication) getApplication()).getApplicationComponent().inject(this);
}
}
public class MyApplication extends Application {
private ApplicationComponent applicationComponent;
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
@Override
public void onCreate() {
super.onCreate();
applicationComponent = ApplicationComponent.Initializer.init(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment