Skip to content

Instantly share code, notes, and snippets.

@gibson-khs
Last active December 29, 2017 02:30
Show Gist options
  • Select an option

  • Save gibson-khs/08a51277286483dcae9aea2377bf3f9f to your computer and use it in GitHub Desktop.

Select an option

Save gibson-khs/08a51277286483dcae9aea2377bf3f9f to your computer and use it in GitHub Desktop.
kotlin_retrofit
class Api {
companion object {
private val BASE_URL = "http://domain/"
private var apiService: ApiInterface? = null
fun getService(): ApiInterface {
if (apiService == null) {
apiService = setApiService()
}
return apiService!!
}
private fun setApiService(): ApiInterface {
val builder = OkHttpClient.Builder()
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
builder.interceptors().add(httpLoggingInterceptor)
val okHttpClient = builder.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
return retrofit.create<ApiInterface>(ApiInterface::class.java)
}
}
}
interface ApiInterface {
@GET("users")
fun getUsers(): Call<MutableList<User>>
}
class Network {
companion object {
fun deafultError(t: Throwable) {
t.printStackTrace()
//TODO
}
fun <T> request(call: Call<T>, callback: NetworkCallback<T>) {
request(call, callback.success!!, callback.error)
}
private fun <T> request(call: Call<T>, onSuccess: (T) -> Unit, onError: ((Throwable) -> Unit)?) {
call.enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>?, response: Response<T>?) {
if (onSuccess != null) {
onSuccess(response?.body()!!)
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
if (onError == null) {
deafultError(t)
} else {
onError(t)
}
}
})
}
}
}
class NetworkCallback<T> {
var success: ((T) -> Unit)? = null
var error: ((Throwable) -> Unit)? = null
}
//use sample
Network.request(Api.getService().getUsers(),
NetworkCallback<MutableList<User>>().apply {
success = {
// it. (MutableList<User>)
}
})
// error handling
Network.request(Api.getService().getUsers(),
NetworkCallback<MutableList<User>>().apply {
success = {
// it. (MutableList<User>)
}
fail = {
// it. (Throwable)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment