Quick setup: Retrofit in Action

Vikram Hooda
1 min readJan 24, 2019

--

This is a quick read story and to the point about retrofit integration in Android application along with object instantiation with/without dagger use.

Required dependencies for retrofit:

//Retrofit, gson converter, RxAdapter dependenices
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

Create RetrofitBuilder.kt object class:

object RetrofitBuilder { 
val BASE_URL: String = “https://abc.com"
fun build(): Retrofit = Retrofit.Builder().apply {
baseUrl(BASE_URL)
addConverterFactory(GsonConverterFactory.create()) addCallAdapterFactory(RxJava2CallAdapterFactory.create())
}.build()
}

Create the instance of service classes and retrofit builder:
With Dagger:

@Module
class ServicesModule {
internal val retrofit: Retrofit
@Singleton
@Provides
get() = RetrofitBuilder.build()
@Singleton
@Provides
internal fun provideABCService(retrofit: Retrofit) = retrofit.create(ABC::class.java)
@Singleton
@Provides
internal fun provideXYZService(retrofit: Retrofit) = retrofit.create(XYZ::class.java)
}

Without dagger:

//Retrofit instance
val retrofit: Retrofit = RetrofitBuilder.build()
OR
val retrofit: RetrofitBuilder.build() //Auto type infer
//Create instanceo of ABC and XYZ service class:
retrofit.create(ABC::class.java)

ABC.kt interface

@get:GET("all")    
val abcData: Observable<List<ABCData>>
@GET("dir/{name}")
fun getData(@Path("name") name: String): Observable<List<ABCData>>

For the complete reference, you can download the complete source code from this link:

https://github.com/vkhooda24/Know-Your-Country-K.

Thanks for reading this story and Let’s make happily coding journey with a clap. :-)

--

--

Vikram Hooda
Vikram Hooda

Written by Vikram Hooda

Love Your Work, World will love you:- VK

No responses yet