Created
May 31, 2017 02:35
-
-
Save socmia/991fdee5ddb0cba2bcad89ae886139d7 to your computer and use it in GitHub Desktop.
We create a class called NetModule.java and annotate it with @module to signal to Dagger to search within the available methods for possible instance providers. The methods that will actually expose available return types should also be annotated with @provides decorator. The Singleton annotation also signals to the Dagger compiler that the inst…
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 | |
public class NetModule { | |
String mBaseUrl; | |
// Constructor needs one parameter to instantiate. | |
public NetModule(String baseUrl) { | |
this.mBaseUrl = baseUrl; | |
} | |
// Dagger will only look for methods annotated with @Provides | |
@Provides | |
@Singleton | |
// Application reference must come from AppModule.class | |
SharedPreferences providesSharedPreferences(Application application) { | |
return PreferenceManager.getDefaultSharedPreferences(application); | |
} | |
@Provides | |
@Singleton | |
Cache provideOkHttpCache(Application application) { | |
int cacheSize = 10 * 1024 * 1024; // 10 MiB | |
Cache cache = new Cache(application.getCacheDir(), cacheSize); | |
return cache; | |
} | |
@Provides | |
@Singleton | |
Gson provideGson() { | |
GsonBuilder gsonBuilder = new GsonBuilder(); | |
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); | |
return gsonBuilder.create(); | |
} | |
@Provides | |
@Singleton | |
OkHttpClient provideOkHttpClient(Cache cache) { | |
OkHttpClient client = new OkHttpClient(); | |
client.setCache(cache); | |
return client; | |
} | |
@Provides | |
@Singleton | |
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) { | |
Retrofit retrofit = new Retrofit.Builder() | |
.addConverterFactory(GsonConverterFactory.create(gson)) | |
.baseUrl(mBaseUrl) | |
.client(okHttpClient) | |
.build(); | |
return retrofit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment