Last active
August 29, 2015 14:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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