Use Retrofit with Dagger - simple example

RetrofitDagger 都是 Square 出的 library,網路上已經有很多相關介紹了,因為 Retrofit 的 REST API Interface 的實作建議採用 Singleton 的方式,所以搭配 Dagger 來管理是個蠻好的 paradigm

今天在這邊分享一個簡單的整合 example,希望可以讓第一次用且想要整合這兩個 libraries 的人快速上手,更 detail 的說明可以參考上面兩個連結~

DaggerModule.java - 提供 injection 的 module,在這裡提供 API Service 的 instance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Module(
injects = {
ExampleActivity.class
}
)
public class DaggerModule {
@Provides
@Singleton
public APIService provideAPIService() {
return new RestAdapter.Builder()
.setEndpoint(Constants.API_SERVICE_ENDPOINT)
.build()
.create(APIService.class);
}
}

上面的 APIService 就是我們 REST API 的 interface

可以把所有的 modules 加在這邊,如此 Dagger 在 compile 時就可以幫我們檢查所有的 modules 裡有沒有錯誤
1
2
3
4
5
6
@Module(
includes = {
DaggerModule.class
}
)
public class WrapperModule {}
ExampleApplication.java - 自己寫一支 custom 的 Application,維護 ObjectGraph,inject 的動作由它執行
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
public class ExampleApplication extends Application {
private ObjectGraph objectGraph;

@Override
public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(new DaggerModule());
}

/**
* inject all injectable fields in this <tt>obj</tt>
* @param obj
*/
public void inject(Object obj) {
objectGraph.inject(obj);
}

/**
* @param activity
* @return instance of ExampleApplication which this activity belongs to
*/
public static ExampleApplication from(Activity activity) {
return (ExampleApplication) activity.getApplication();
}
}

記得在 AndroidManifest.xml<application> tag 加上 android:name 屬性,指定 custom Application 的 class

BaseActivity.java - 之後我們寫的 Activity 只要繼承它,擁有 @inject 的屬性就會自動被注入
1
2
3
4
5
6
7
8
9
public abstract class BaseActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExampleApplication.from(this).inject(this);
}

}
ExampleActivity.java
1
2
3
4
5
public class ExampleActivity extends BaseActivity {
@Inject
APIService apiService;
......
}

接下來就可以在 ExampleActivity 中自由使用 apiService 啦!

評論

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×