Skip to content

Instantly share code, notes, and snippets.

@UtkuGlsvn
Last active May 17, 2021 10:30
Show Gist options
  • Save UtkuGlsvn/21346ad0f3942ab50272cd4775666988 to your computer and use it in GitHub Desktop.
Save UtkuGlsvn/21346ad0f3942ab50272cd4775666988 to your computer and use it in GitHub Desktop.
Benzinlitre Rest Service Retrofit
class Repository @Inject constructor(private val source: GetPostSource) {
suspend fun postRequest(paramsmap: HashMap<String, Any>) {
when (val result = source.executePostService(paramsmap)) {
is Resource.Success -> {
val resBody = gson.toJson(result.data.result)
val res = gson.fromJson(resBody, entity::class.java) // you entity class
//.....
}
is Resource.Error -> errorMessage.postValue(result.message)
else -> Timber.i("Service Error")
}
}
suspend fun getRequest() {
when (val result = source.executeGetService(paramsmap)) {
is Resource.Success -> {
val resBody = gson.toJson(result.data.result)
val res = gson.fromJson(resBody, entity::class.java) // you entity class
//.....
}
is Resource.Error -> errorMessage.postValue(result.message)
else -> Timber.i("Service Error")
}
}
class GetPostSource @Inject constructor(private val service: InterfaceApi) :
BaseUseCase() {
suspend fun executeGetService(): Resource<Any> =
getResource { service.getAPI("getEndPoint") }
suspend fun executePostService(paramsMap: HashMap<String, Any>): Resource<Any> =
getResource { service.postAPI("getEndPoint",paramsMap) }
}
@POST suspend fun postAPI(@Url url: String?, @Body body:HashMap<String, @JvmSuppressWildcards Any>): Response<Any>
@GET suspend fun getAPI(@Url url: String?): Response<Any>
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Singleton
@Provides
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
if (BuildConfig.DEBUG) {
this.level = HttpLoggingInterceptor.Level.BODY
}
}
@Singleton
@Provides
fun provideOkHttpClient(interceptor: HttpLoggingInterceptor): OkHttpClient =
OkHttpClient.Builder().apply {
this.addInterceptor(interceptor)
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.addInterceptor { chain ->
chain.request().newBuilder()
.addHeader("...", "...") //Header Request
.build()
chain.proceed(newRequest)
}
}.build()
@Singleton
@Provides
fun provideGsonConverterFactory(): Converter.Factory =
GsonConverterFactory.create()
@Singleton
@Provides
fun providesRetorfit(
converter: Converter.Factory,
okHttpClient: OkHttpClient
): Retrofit =
Retrofit.Builder()
.baseUrl(ServiceConstants.BASE_URL)
.addConverterFactory(converter)
.client(okHttpClient)
.build()
@Singleton
@Provides
fun providesApiService(retrofit: Retrofit): InterfaceApi =
retrofit.create(InterfaceApi::class.java)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment