【生意多】-免费发布分类信息
当前位置: 首页 » 新闻 » 教程 » 操作系统 » 正文

使用打造简单的请求库

放大字体  缩小字体 发布日期:2022-07-02 19:21:49    浏览次数:14

基于 kotlin/coroutine/retrofit/jetpack 打造,100来行代码,用法超级简单舒适

设置默认Retrofit工厂和全局错误处理程序

1
2
3
4
5
HttpCall.init(retrofitFactory = {
  // ...
}, errorHandler = { throwable ->
  // ...
})

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
repositories {
  maven { url "https://gitee.com/ezy/repo/raw/android_public/"}
}
dependencies {
  implementation "me.reezy.jetpack:httpcall:0.4.0"
}
 
(文/小编)
打赏
免责声明
• 
本文为小编原创作品,作者: 小编。欢迎转载,转载请注明原文出处:http://www.31duo.com/news/show-3613655.html 。本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们。
 

(c)2016-2019 31DUO.COM All Rights Reserved浙ICP备19001410号-4

浙ICP备19001410号-4