Kotlin + Retrofit + RxJava简单封装使用详解

网友投稿 512 2023-01-26


Kotlin + Retrofit + RxJava简单封装使用详解

本文介绍了Kotlin + Retrofit + Rxjava简单封装使用详解,分享给大家,具体如下:

实例化Retrofit

object RetrofitUtil {

val CONNECT_TIME_OUT = 30//连接超时时长x秒

val READ_TIME_OUT = 30//读数据超时时长x秒

val WRITE_TIME_OUT = 30//写数据接超时时长x秒

val retrofit: Retrofit by lazy {

Log.d("RetrofitUtil", "retrofit init lazy")

Retrofit.Builder()

.baseUrl("http://gank.io/api/") //本文以github API为例

.addConverterFactory(GsonConverterFactory.create())

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

.client(getOkHttpClient())

.build()

}

private fun getOkHttpClient(): OkHttpClient {

val builder = OkHttpClient.Builder()

builder.connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)

.writeTimeout(WRITE_TIME_OUT.toLong(), TimeUnit.SECONDS)

.readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)

if (BuildConfig.DEBUG) {

builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))

} else {

builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE))

}

// 设置请求头

builder.addInterceptor { chain ->

val time = (System.currentTimeMillis() / 1000).toString() + ""

val requestBuilder = chain.request().newBuilder()

requestBuilder.addHeader("time", time)

chain.proceed(requestBuilder.build())

}

return builder.build()

}

}

返回数据封装

class Response {

var error: Boolean = false

var results: T? = null

}

demo中用了gank.io的开发api,之前一般项目的返回格式是code + message + T的格式。

api接口错误/异常统一处理类

class ApiException : Exception {

var code: Int = 0//错误码

var msg: String? = null//错误信息

constructor(throwable: Throwable, code: Int) : super(throwable) {

this.code = code

}

constructor(code: Int, msg: String) {

this.code = code

this.msg = msg

}

}

定义ExceptionFunction处理onErrorResumeNext:

class ExceptionFunction : Function> {

override fun apply(@NonNull throwable: Throwable): Observable {

Log.e("ExceptionFunction", throwable.message)

return Observable.error(ExceptionEngine().handleException(throwable))

}

}

/**

* 错误/异常处理工具

*/

class ExceptionEngine {

val UN_KNOWN_ERROR = 1000//未知错误

val ANALYTIC_SERVER_DATA_ERROR = 1001//解析(服务器)数据错误

val CONNECT_ERROR = 1002//网络连接错误

val TIME_OUT_ERROR = 1003//网络连接超时

fun handleException(e: Throwable): ApiException {

val ex: ApiException

if (e is ApiException) { //服务器返回的错误

return e

} else if (e is HttpException) { //HTTP错误

ex = ApiException(e, e.code())

ex.msg = "网络错误:" + ex.code

return ex

} else if (e is jsonParseException

|| e is JSONException

|| e is ParseException || e is MalformedJsonException) { //解析数据错误

ex = ApiException(e, ANALYTIC_SERVER_DATA_ERROR)

ex.msg = "解析错误"

return ex

} else if (e is ConnectException) {//连接网络错误

ex = ApiException(e, CONNECT_ERROR)

ex.msg = "连接失败"

return ex

} else if (e is SocketTimeoutException) {//网络超时

ex = ApiException(e, TIME_OUT_ERROR)

ex.msg = "网络超时"

return ex

} else { //未知错误

ex = ApiException(e, UN_KNOWN_ERROR)

ex.msg = e.message

return ex

}

}

}

封装请求处理

object Rx {

/**

* Rxlifecycle绑定生命周期

*/

fun get(observable: Observable>, lifecycleProvider: LifecycleProvider): Observable {

// 请求绑定生命周期,防止内存泄漏,同时返回回调之后页面已销毁造成的空指针错误

if (lifecycleProvider is RxAppCompatActivity) {

val rxAppCompatActivity = lifecycleProvider as RxAppCompatActivity

observable.compose(rxAppCompatActivity.bindUntilEvent(ActivityEvent.DESTROY))

} else if (lifecycleProhttp://vider is RxFragment) {

val rxFragment = lifecycleProvider as RxFragment

observable.compose(rxFragment.bindUntilEvent(FragmentEvent.DESTROY))

}

return observable

.compose(HandleResult())

.onErrorResumeNext(ExceptionFunction())

}

/**

* 部分后台请求

*/

fun get(observable: Observable>): Observable {

return observable

.compose(HandleResult())

.onErrorResumeNext(ExceptionFunction())

}

private class HandleResult : ObservableTransformer, T> {

override fun apply(upstream: Observable>): ObservableSource {

return upstream.flatMap { response -> createResult(response) }

.subscribeOn(Schedulers.io())

.unsubscribeOn(Schedulers.io())

.observeOn(androidSchedulers.mainThread())

}

}

private fun createResult(response: Response): Observable {

return Observable.create({ subscriber ->

if (response.error)

throw ApiException(-1, "服务器异常") // 一般来说,自己的服务器异常会返回相应的code和message

else

response.results?.let {

subscriber.onNext(response.results!!)

} ?: subscriber.onComplete()

})

}

}

定义HttpObserver统一处理返回

abstract class HttpObserver : Observer {

/**

* 标记是否为特殊情况

*/

private var resultNull: Boolean = true

override fun onComplete() {

// 特殊情况:当请求成功,但T == null时会跳过onNext,仍需当成功处理

if (resultNull)

onSuccess(null)

}

override fun onSubscribe(d: Disposable) {

// 可在此处加上dialog

}

override fun onError(e: Throwable) {

if (e is ApiException) {

onError(e.code, e.msg)

} else {

onError(0, e.message)

}

}

override fun onNext(t: T) {

resultNull = false

onSuccess(t)

}

abstract fun onSuccess(t: T?)

/**

* 统一处理失败,比如登录失效等

*

* @param code

* @param msg

*/

open fun onError(code: Int, msg: String?) {

}

}

Api

class Result {

var _id: String? = null

var createdAt: String? = null

var desc: String? = null

var publishedAt: String? = null

var source: String? = null

var type: String? = null

var url: String = ""

var isUsed: Boolean = false

var who: String? = null

var images: List? = null

/**

* 妹子小图

*/

fun meiziSmallUrl(): String {

val meizi = url

return meizi.replace("large", "small")

}

}

interface Apiservice {

@GET("data/{type}/10/{page}")

fun getGank(@Path("type") type: String, @Path("page") page: Int): Observable>>

}

object Api {

val apiservice: Apiservice by lazy {

Log.d("Api", "apiservice create lazy")

RetrofitUtil.retrofit.create(Apiservice::class.java)

}

}

使用

override fun loadData() {

Rx.get(Api.apiservice.getGank(getType(), mIntPage), this).subscribe(object : HttpObserver>() {

override fun onSuccess(t: List?) {

//getDataSuccess(t)

}

override fun onError(code: Int, msg: String?) {

super.onError(code, msg)

//getDataFailed()

}

})

}

使用了Rxlifecycle绑定生命周期来处理可能发生的内存泄漏问题,Fragment跟Activity需要继承Rx相应的基类。

练手项目

Meizikt Gank.io Android客户端,使用Kotlin + Retrofit2 + RxJava


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Vue自定义指令封装节流函数的方法示例
下一篇:无线连接共享文件夹(电脑无线共享文件夹)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~