您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本文介绍了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<T> { 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<T> : Function<Throwable, Observable<T>> { override fun apply(@NonNull throwable: Throwable): Observable<T> { 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 <T, E> get(observable: Observable<Response<T>>, lifecycleProvider: LifecycleProvider<E>): Observable<T> { // 请求绑定生命周期,防止内存泄漏,同时返回回调之后页面已销毁造成的空指针错误 if (lifecycleProvider is RxAppCompatActivity) { val rxAppCompatActivity = lifecycleProvider as RxAppCompatActivity observable.compose(rxAppCompatActivity.bindUntilEvent(ActivityEvent.DESTROY)) } else if (lifecycleProvider is RxFragment) { val rxFragment = lifecycleProvider as RxFragment observable.compose(rxFragment.bindUntilEvent(FragmentEvent.DESTROY)) } return observable .compose(HandleResult()) .onErrorResumeNext(ExceptionFunction()) } /** * 部分后台请求 */ fun <T> get(observable: Observable<Response<T>>): Observable<T> { return observable .compose(HandleResult()) .onErrorResumeNext(ExceptionFunction()) } private class HandleResult<T> : ObservableTransformer<Response<T>, T> { override fun apply(upstream: Observable<Response<T>>): ObservableSource<T> { return upstream.flatMap { response -> createResult(response) } .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } } private fun <T> createResult(response: Response<T>): Observable<T> { 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<T> : Observer<T> { /** * 标记是否为特殊情况 */ 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<String>? = 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<Response<List<Result>>> } 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<List<Result>>() { override fun onSuccess(t: List<Result>?) { //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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。