我是靠谱客的博主 妩媚鸡翅,这篇文章主要介绍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" 
}

最后

以上就是妩媚鸡翅最近收集整理的关于Android使用 Coroutine + Retrofit打造简单的HTTP请求库的全部内容,更多相关Android使用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(121)

评论列表共有 0 条评论

立即
投稿
返回
顶部