티스토리 뷰

개발/안드로이드

Android Dagger2 적용

임뒤 2017. 10. 12. 17:19

http://kunny.github.io/life/2016/06/06/dagger2_resources/


요기에 Jake Wharton 형님이 발표하신거 나오니까 고거 참고.


Dagger2 왜 하냐? New 없앨라고 한다. 안에 내용 이해하려면 골치 아픔.

Dependency Inspection을 하기 위해선데, 이게 뭔지 알아야하고, 이걸 왜 하냐면

패턴 중에 Inversion Of Control 패턴 적용 시 사용됨.


http://www.kmshack.kr/2017/06/dagger-2-소개-안드로이드에서-dependency-injection-사용하기전에/

자세한 건 여기에.


https://blog.mindorks.com/introduction-to-dagger-2-using-dependency-injection-in-android-part-2-b55857911bcd

예제 코드를 통한 실전 연습은 이 코드로 하셈.


가장 중요한 개념은


공급하는 놈이 있고, 소비하는 놈이 있다. 그리고 그 중간을 연결해주는 놈이 있다.


@Module, @Provide 공급하는 놈.

@Inject 소비하는 놈.

@Component 연결하는 놈.


그니까 우선은 우리가 공급을 해야 소비를 하잖아.

1. 공급자를 만든다.

2. 소비자를 만든다.

3. 공급자와 소비자를 연결해준다.


@Module
public class ActivityModule {

private Activity mActivity;

public ActivityModule(Activity activity) {
mActivity = activity;
}

@Provides
@ActivityContext
Context provideContext() {
return mActivity;
}

@Provides
Activity provideActivity() {
return mActivity;
}
}

대충 이렇게 공급하고

@Inject
DataManager mDataManager;
@Inject
public DataManager(@ApplicationContext Context context,
DbHelper dbHelper,
SharedPrefsHelper sharedPrefsHelper) {
mContext = context;
mDbHelper = dbHelper;
mSharedPrefsHelper = sharedPrefsHelper;
}

대충 이렇게 소비하면 됨.

소비할 때는 3개가 소비 가능하댄다.


1. 생성자

2. 메소드

3. 필드


생성자랑 필드는 위의 예시에서 나옴. 메소드는 어떻게 하는지 잘 모르겠음. 그냥 하지 마셈.


그 담에 이제 공급 소비 연결하면 끝.

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

void inject(DemoApplication demoApplication);

@ApplicationContext
Context getContext();

Application getApplication();

DataManager getDataManager();

SharedPrefsHelper getPreferenceHelper();

DbHelper getDbHelper();
}
public ActivityComponent getActivityComponent() {
if (activityComponent == null) {
activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(this))
.applicationComponent(DemoApplication.get(this).getComponent())
.build();
}
return activityComponent;
}
getActivityComponent().inject(this);

이렇게 연결하면 됨.


여기서 중요한 워크 플로우는 Component가 Singlton으로 되어 있어서, 기존에 만든 객체는 남아서 바로 가져다 쓴다는 사실이다.


92쪽부터 125쪽까지 Jake Wharton 행님의 프레젠테이션을 참고하라.


이상 Dagger2 적용 끝. 자세한 건 더 못쓰겠다.

'개발 > 안드로이드' 카테고리의 다른 글

Android Location Api  (0) 2017.10.24
Android Action bar Style Setting  (0) 2017.10.23
Android Dialog  (0) 2017.10.12
Android Data Binding  (0) 2017.10.12
Android ButterKnife 적용  (0) 2017.10.11
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31