Android使用 Coroutine + Retrofit打造簡單的HTTP請求庫

基於 kotlin/coroutine/retrofit/jetpack 打造,100來行代碼,用法超級簡單舒適

設置默認Retrofit工廠和全局錯誤處理程序

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

基本用法

data class Reault(val data:String)

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

// 在 activity/fragment 中使用,獲取請求結果
http<TestService>().test().result(this) {
  // it 是 Reault
}

// 在 activity/fragment 中使用,獲取請求響應對象
http<TestService>().test().response(this) {
  // it 是 Response<Result>
}

顯示請求狀態,基於 HttpCall擴展出 withSpinning 方法

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) 

引入

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" 
}

推薦閱讀: