一、升级版:通过注解强化ApiService实例在各种开发环境中的自动化构建;对接口方法提供内部封装实现更多功能;
一、接口声明
package com.chenliang.account
typealias Data<T> = Call<BaseResponse<T>>
typealias Datas<T> = Call<BaseResponse<ArrayList<T>>>
@MyApiService(
mName = "API",
mPath = "http://www.chenliang.com/app/",
mDevPath = "http://www.chenliang.com/dev/app/",
mTestPath = "http://www.chenliang.com/test/app/"
)
interface ApiService {
@MyRetrofitGo(mTag = "登录", mLoading = true, mFailToast = true)
@POST("home/login")
fun login(
@Query("account") account: String,
@Query("password") password: String
): Data<BeanUser>
@MyRetrofitGo(mTag = "注册", mLoading = true, mFailToast = true)
@POST("home/register")
fun register(
@Query("account") account: String,
@Query("password") password: String
): Data<BeanUser>
@MyRetrofitGo(mTag = "添加测试", mCache = false, mFailToast = true)
@POST("home/add")
fun addTest(
@Query("account") account: String,
@Query("password") password: String
): Data<BeanUser>
}
@MyApiService注解说明:
mName: API接口名称
mPath: API接口生产环境base路径
mDevPath: API接口开发环境base路径
mTestPath: API接口测试环境base路径
@MyRetrofitGo注解说明:
mLoading: 是否显示loading加载框
mCache:是否启用缓存
mHasCacheLoading:缓存存在情况下是否显示loading加载狂
mFailToast:接口失败时,是否自动toast提示message信息
mSuccessCode:接口成功后,接口内部调用RxBus自动发送的code值
mFailCode: 接口失败后,接口内部使用RxBus自动发送的code值
二、ViewModel中调用接口:
通过@MyApiService注解mName定义的名称,直接调用接口方法
package com.chenliang.account.vm
class AccountViewModel : MyBaseViewModel() {
fun login(account: String, pass: String) = go { API.login(account, pass) }
fun register(account: String, pass: String) = go { API.register(account, pass) }
}
三、自定义ViewModel使用:
mViewModel.login(user.name, user.password).obs(this@LoginActivity) {
it.c { //缓存数据 }
it.y { //请求成功 }
it.n { //请求失败 }
}
查看封装细节,请查看github代码:
https://github.com/chenliangj2ee/Android-MVVM-Component-Jetpack-Kotlin
注解强化Retrofit自动化构建实践
本文介绍了如何通过注解@MyApiService和@MyRetrofitGo增强Retrofit在不同开发环境中的自动化构建,同时在接口方法内部实现更多功能。在ViewModel中,可以通过注解的接口名称直接调用接口方法,简化了调用流程。详细封装细节可查阅GitHub上的代码仓库。
844

被折叠的 条评论
为什么被折叠?



