class LiveDataRetrofitActivity:AppCompatActivity() {
private lateinit var viewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_livedata)
viewModel= ViewModelProvider(this).get(LoginViewModel::class.java)
}
fun login(view: View) {
viewModel.login(LoginVo("123456","admin"))
.observe(this,
Observer<BaseDto<LoginDto>> { t ->
t?.let {loginDtoBaseDto->
if (loginDtoBaseDto.meta?.status == 200){
SPUtil.setString(Constant.TOKEN,loginDtoBaseDto.data?.token.toString())
Log.e("AAA",loginDtoBaseDto.data?.token.toString())
}else{
Log.e("AAA",loginDtoBaseDto.meta?.message.toString())
}
}
})
}
fun deleteRoute(view: View) {
viewModel.deleteRoute("16cb1536859f46c6960551ad83b293c2")
.observe(this,
Observer<BaseDto<String?>> { t ->
Log.e("DELETE:",Gson().toJson(t))
})
}
}
class LoginViewModel:ViewModel() {
fun login(loginVo: LoginVo):LiveData<BaseDto<LoginDto>>{
return LoginRepository().login(loginVo)
}
fun deleteRoute(id:String):LiveData<BaseDto<String?>>{
return LoginRepository().deleteRoute(id)
}
fun sysUserPaging(pageNum: Int, pageSize: Int): LiveData<BaseDto<SysUserDto>>{
return LoginRepository().sysUserPaging(pageNum,pageSize)
}
}
class LoginRepository : BaseRepository(), ILoginRepository, IRouteRepository, ISysUserRepository {
override fun login(loginVo: LoginVo): LiveData<BaseDto<LoginDto>> {
return request(
RequestRetrofit.getInstance(ApiService::class.java).login(loginVo)
).data
}
override fun deleteRoute(id: String): LiveData<BaseDto<String?>> {
return request(
RequestRetrofit.getInstance(ApiService::class.java).patrolRouteDeleteId(id)
).data
}
override fun sysUserPaging(pageNum: Int, pageSize: Int): LiveData<BaseDto<SysUserDto>> {
return request(
RequestRetrofit.getInstance(ApiService::class.java).sysUserPaging(pageNum, pageSize)
).data
}
}
object RequestRetrofit {
/**
* 创建okhttp相关对象
*/
private var okHttpClient: OkHttpClient? = null
private var retrofit: Retrofit? = null
fun <T> getInstance(service: Class<T>): T {
if (okHttpClient == null) {
synchronized(RequestRetrofit::class.java) {
if (okHttpClient == null) {
okHttpClient = OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor {
//访问网络请求,和服务端响应请求时。将数据拦截并输出
if ("401" in it) SPUtil.remove(Constant.TOKEN)
Log.e("HTTP", it)
}.setLevel(HttpLoggingInterceptor.Level.BODY)
)
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addNetworkInterceptor(StethoInterceptor())
.addInterceptor(AddCookiesInterceptor())
// .addInterceptor(ReceivedCookiesInterceptor())
.build()
}
}
}
if (retrofit == null) {
synchronized(RequestRetrofit::class.java) {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(ApiConfig.BaseUrl)
.client(okHttpClient!!)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
}
}
}
return retrofit!!.create(service)
}
}
class BaseDto<T> : Serializable{
var meta: MetaData?=null
var data: T?=null
}
data class MetaData(
var message: String?,
var status: Int,
var success: Boolean
)
open class BaseRepository {
/**
* 请求网络
* @param flowable
* @param <T>
* @return
*/
fun <T> request(flowable: Flowable<BaseDto<T>>): BaseHttpSubscriber<T> {
val baseHttpSubscriber = BaseHttpSubscriber<T>() //RxJava Subscriber回调
flowable.subscribeOn(Schedulers.io()) //解决背压
.observeOn(AndroidSchedulers.mainThread())
.subscribe(baseHttpSubscriber)
return baseHttpSubscriber
}
}
class PageKeyedSource : PagingSource<Int, SysUserInfo>() {
override fun getRefreshKey(state: PagingState<Int, SysUserInfo>): Int? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey
}
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, SysUserInfo> {
return try {
//页码未定义置为1
val currentPage = params.key ?: 1
val data = RequestRetrofit.getInstance(ApiService::class.java).sysUserPaging2(
currentPage,
20
).data
val nextPage = if (currentPage < data?.pages?:0){
currentPage + 1
}else{
null
}
if (data != null) {
LoadResult.Page(
data = data.list,
prevKey = null,
nextKey = nextPage
)
} else {
LoadResult.Error(throwable = Throwable())
}
} catch (e: IOException) {
LoadResult.Error(e)
} catch (e: HttpException) {
LoadResult.Error(e)
}
}
}
interface ILoginRepository {
fun login(loginVo: LoginVo): LiveData<BaseDto<LoginDto>>?
}
interface IRouteRepository {
fun deleteRoute(id: String): LiveData<BaseDto<String?>>?
}
interface ISysUserRepository {
fun sysUserPaging(pageNum: Int, pageSize: Int): LiveData<BaseDto<SysUserDto>>?
}
代码是19年写的了,发上来留个念。AddCookiesInterceptor里只是一个header注入,根据自己实际情况来
|