这篇文章主要介绍了Android使用 Coroutine + Retrofit打造简单的HTTP请求库,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下
基于 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 Studio突然不显示logcat日志的问题 2023-02-04
- android studio按钮监听的5种方法实例详解 2023-01-12
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
- Android多返回栈技术 2023-04-15
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- Android中的webview监听每次URL变化实例 2023-01-23
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
- Flutter手势密码的实现示例(附demo) 2023-04-11
