I have the following setup:
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(5, TimeUnit.SECONDS);
okHttpClient.setConnectTi
Kotlin
If you want to use Retrofit in Kotlin follow below steps:
Define your Retrofit interface:
interface GitHubApi {
@GET("/users/{userName}/repos")
fun repos(@Path("userName") userName: String): Call>
}
Implement your service:
class Api(...) {
private val baseUrl = "https://api.github.com"
private val api: GitHubApi
private fun loggingInterceptor(...): HttpLoggingInterceptor {...}
private fun okHttpBuilder(): OkHttpClient {...}
init {...}
fun repos(
userName: String,
onSuccess: (list: List?) -> Unit,
onFailure: (message: String?) -> Unit): Future {
return runAsync(api.repos(userName), onSuccess, onFailure)
}
private fun runAsync(
call: retrofit2.Call,
onSuccess: (T?) -> Unit,
onFailure: (message: String?) -> Unit) : Future {
return doAsync {
try {
val response = call.execute()
when {
response.isSuccessful -> response.body()?.let {
onSuccess(it)
}
else -> {
onFailure(response.raw().message())
}
}
} catch (e: IOException) {
if (e is SocketTimeoutException) {
onFailure("Response time out!")
} else {
onFailure(e.message)
}
}
}
}
}
Call your service in where you want:
Api().repos("olcayertas",
onSuccess = {
Log.d("MainActivity", "Response:\n" + toJson(it))
},
onFailure = {
Log.e("MainActivity", "Error: $it")
})
You can handle any exception you want in runAsync function.
You can get fully working example here.