Android uses Coroutine + Retrofit to create a simple HTTP request library

  • 2021-12-11 19:08:54
  • OfStack

Based on kotlin/coroutine/retrofit/jetpack, 100 lines of code, super simple and comfortable usage

Setting the default Retrofit factory and global error handler


HttpCall.init(retrofitFactory = {
  // ...
}, errorHandler = { throwable ->
  // ...
}) 

Basic usage


data class Reault(val data:String)

interface TestService { 
  @GET("test")
  fun test(): Call<Reault> 
} 

//  In  activity/fragment  To get the result of the request 
http<TestService>().test().result(this) {
  // it  Yes  Reault
}

//  In  activity/fragment  To get the request response object 
http<TestService>().test().response(this) {
  // it  Yes  Response<Result>
}

Display the request status and extend the withSpinning method based on HttpCall


fun <T : Any> HttpCall<T>.withSpinning(activity: FragmentActivity, spinning: Boolean = false, text: String = ""): HttpCall<T> {
  activity.apply {
    if (isFinishing || isDestroyed) return@apply
    val dialog = showLoading(spinning, text)

    finally { dialog.dismiss() }
  }
  return this
}


http<TestService>().test().result(this) {
  Log.e("api", it.data)
}.withSpinning(this) 

Introduce

https://github.com/czy1121/httpcall


repositories { 
  maven { url "https://gitee.com/ezy/repo/raw/android_public/"}
} 
dependencies {
  implementation "me.reezy.jetpack:httpcall:0.4.0" 
}


Related articles: