Create a gist now

Instantly share code, notes, and snippets.

Embed
Sources for blog post "Dependency injection with Dagger 2 - Introdution to DI"
public class LoginActivity extends AppCompatActivity {
LoginActivityPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OkHttpClient okHttpClient = new OkHttpClient();
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setClient(new OkClient(okHttpClient));
RestAdapter restAdapter = builder.build();
ApiService apiService = restAdapter.create(ApiService.class);
UserManager userManager = UserManager.getInstance(apiService);
UserDataStore userDataStore = UserDataStore.getInstance(
getSharedPreferences("prefs", MODE_PRIVATE)
);
//Presenter is initialized here
presenter = new LoginActivityPresenter(this, userManager, userDataStore);
}
}
public class LoginActivity extends AppCompatActivity {
@Inject
LoginActivityPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Satisfy all dependencies requested by @Inject annotation
getDependenciesGraph().inject(this);
}
}
class UserManager {
private ApiService apiService;
private UserStore userStore;
//Dependencies are passed as arguments
public UserManager(ApiService apiService, UserStore userStore) {
this.apiService = apiService;
this.userStore = userStore;
}
void registerUser() {/* */}
}
class RegisterActivity extends Activity {
private UserManager userManager;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
ApiService api = ApiService.getInstance();
UserStore store = UserStore.getInstance();
this.userManager = new UserManager(api, store);
}
public void onRegisterClick(View v) {
userManager.registerUser();
}
}
class UserManager {
private ApiService apiService;
private UserStore userStore;
//No-args constructor. Dependencies are created inside.
public UserManager() {
this.apiService = new ApiSerivce();
this.userStore = new UserStore();
}
void registerUser() {/* */}
}
class RegisterActivity extends Activity {
private UserManager userManager;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
this.userManager = new UserManager();
}
public void onRegisterClick(View v) {
userManager.registerUser();
}
}
public class UserManagerTests {
UserManager userManager;
@Mock
ApiService apiServiceMock;
@Mock
UserStore userStoreMock;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
userManager = new UserManager(apiServiceMock, userStoreMock);
}
@After
public void tearDown() {
}
@Test
public void testSomething() {
//Test our userManager here - all its dependencies are satisfied
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment