Skip to content

Instantly share code, notes, and snippets.

@hannesstruss
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hannesstruss/827dad670971456adb8b to your computer and use it in GitHub Desktop.
Save hannesstruss/827dad670971456adb8b to your computer and use it in GitHub Desktop.
Treat an object as a singleton in one scope, the Yo-Dawg way
@Module(injects = MyActivityModule.class)
class MotherModule {
// ...snip
}
@Module(
addsTo = MotherModule.class,
injects = {MyActivity.class, MyFragment.class}
)
class MyActivityModule {
private MyPresenter presenter;
@Inject public SubModule(MyPresenter presenter) {
this.presenter = presenter;
}
@Provides @Singleton MyPresenter providePresenter() {
return presenter;
}
}
class MyPresenter {
@Inject public MyPresenter(Database database, View view) {
// ...snip
}
}
class MyActivity extends Activity {
private ObjectGraph activityObjectGraph;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ObjectGraph motherGraph = ((MyApp) getApplication()).getObjectGraph();
activityObjectGraph = motherGraph.plus(motherGraph.get(MyActivityModule.class);
}
public void inject(Object object) {
activityObjectGraph.inject(object);
}
}
class MyFragment extends Fragment {
public void onActivityCreated() {
((MyActivity) getActivity()).inject(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment