Skip to content

Instantly share code, notes, and snippets.

@MrTact
Last active April 29, 2019 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrTact/0fddded4fa55c32cbec0451d6af315d7 to your computer and use it in GitHub Desktop.
Save MrTact/0fddded4fa55c32cbec0451d6af315d7 to your computer and use it in GitHub Desktop.
Object wrapper to easily create a retrofit client in Kotlin
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
/**
* @return A callable instance of a retrofit client based on the provided API class
*
* @param baseUrl: The base URL for the api host
* @param apiClass: A Java class instance of the (usually) interface that implements the method calls for the
* various endpoints, annotated with the appropriate Retrofit annotations.
* @params mapperModules: Optional list of modules to add to the Jackson object mapper (e.g. JodaModule)
*/
object RetrofitClient {
fun <T> get(baseUrl: String, apiClass: Class<T>, mapperModules: List<SimpleModule> = emptyList()): T {
val mapper = ObjectMapper()
.registerModule(KotlinModule())
.also { objectMapper ->
mapperModules.forEach { objectMapper.registerModule(it) }
}
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.build()
.create(apiClass)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment