Last active
May 31, 2017 13:48
-
-
Save danilosilvadev/8c8de30e668d851d66def09c0f713ab8 to your computer and use it in GitHub Desktop.
Dagger2 in 3 minutes
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
//SHALL WE BEGIN? | |
//FILE 1 - THE MODULE | |
@Module //MODULE IS WHAT YOU WANT TO INSTANTIATE. | |
public class UserLoginModule { | |
@Provides //@PROVIDES RELEASE THE OBJECT TO INJECTION. | |
@PerActivity //@PERACTIVITY IS THE SCOPE, LIKE BOUNDS WHERE YOU CAN USE THAT. | |
public UserModel getUser(){ | |
return new UserModel(); | |
} | |
} | |
//FILE 2 - THE COMPONENT | |
@PerActivity | |
@Component(modules = {UserLoginModule.class}) | |
public interface MainComponent { | |
//COMPONENT IS WHERE YOU WANT INSTANTIATE THE @PROVIDES METHODS OF THE MODULE. | |
void injectIntoMainActivity(MainActivity mainActivity); | |
//GradeResponse injectIntoGradeResponse(GradeResponse gradeResponse); --> this you | |
//can use to inject into classes that aren't activities. | |
} | |
//FILE 3 - THE MYAPPLICATION | |
public class MyApplication extends Application { | |
//"MYAPPLICATION" IS A RELEASE OF THE DAGGER2 INSTANCE AND COMPONENTS TO ALL CLASSES. | |
private static MainComponent mainComponent; | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
initDagger(); | |
} | |
private void initDagger() { | |
mainComponent = DaggerMainComponent | |
.builder() | |
.userModule(new UserModule()) | |
.build(); | |
} | |
public static MainComponent getMainComponent() { | |
return mainComponent; | |
} | |
} | |
//FILE 4 - THE MAIN/ANOTHER CLASS | |
//INSIDE ONCREATE PUT THIS: | |
MyApplication.getMainComponent().injectIntoMainActivity(this); | |
//OR INSIDE A METHOD OF ANOTHER CLASS THAT IS NOT AN ACTIVITY: | |
MyApplication.getMainComponent().injectIntoAnotherClass(this); | |
//STILL ON FILE 4, ON GLOBAL SCOPE OF THE CLASS: | |
@Inject //@INJECT IS THE OBJECT THAT YOU WANT TAKE FROM MODULE. | |
UserModel userModel; | |
//FILE 5 - SCOPE | |
@Scope | |
@Retention(RetentionPolicy.CLASS) | |
public @interface PerInstance {} | |
//Dont forget inside the manifest: | |
<Application | |
android:allowBackup="true" | |
android:name="MyApplication"> | |
//NOW LET'S PUT A SMILE ON THAT FACE - YOU LEARNED FUCKING DAGGER2 IN LESS THAN FIVE MINUTES. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment