Skip to content

Instantly share code, notes, and snippets.

@VladimirMi
Last active February 22, 2018 08:03
Show Gist options
  • Save VladimirMi/e7faf875f2aed3faac8b1d837ea89483 to your computer and use it in GitHub Desktop.
Save VladimirMi/e7faf875f2aed3faac8b1d837ea89483 to your computer and use it in GitHub Desktop.
Application
/**
* Class for maintaining global application state.
*/
public class App extends Application {
private static DataManager sDataManager;
@Override
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
sDataManager = new DataManager(RestServiceProvider.getService());
}
public static DataManager getDataManager() {
return sDataManager;
}
}
/**
* Rest service interface
*/
public interface RestService {
@GET("movie/popular")
Single<PaginatedMoviesResult> getPopular(@Query("page") int page);
@GET("movie/top_rated")
Single<PaginatedMoviesResult> getTopRated(@Query("page") int page);
}
/**
* Provider for {@link RestService}, witch is a singleton.
*/
public class RestServiceProvider {
private final static String BASE_URL = "https://api.themoviedb.org/3/";
private final static int CONNECT_TIMEOUT = 5000;
private final static int READ_TIMEOUT = 5000;
private final static int WRITE_TIMEOUT = 5000;
private static class ServiceHolder {
private static final RestService instance = createRetrofit(createClient())
.create(RestService.class);
}
private RestServiceProvider() {
}
public static RestService getService() {
return ServiceHolder.instance;
}
private static OkHttpClient createClient() {
return new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.addNetworkInterceptor(new StethoInterceptor())
.addInterceptor(getApiKeyInterceptor())
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
.build();
}
private static Retrofit createRetrofit(OkHttpClient okHttp) {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(createConvertFactory())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.client(okHttp)
.build();
}
private static Converter.Factory createConvertFactory() {
return MoshiConverterFactory.create();
}
private static Interceptor getApiKeyInterceptor() {
return chain -> {
Request originalRequest = chain.request();
HttpUrl url = originalRequest.url().newBuilder()
.addQueryParameter("api_key", BuildConfig.API_KEY)
.build();
Request request = originalRequest.newBuilder()
.url(url)
.build();
return chain.proceed(request);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment