您好,登錄后才能下訂單哦!
本文介紹了Kotlin + Retrofit + RxJava簡(jiǎn)單封裝使用詳解,分享給大家,具體如下:
實(shí)例化Retrofit
object RetrofitUtil { val CONNECT_TIME_OUT = 30//連接超時(shí)時(shí)長(zhǎng)x秒 val READ_TIME_OUT = 30//讀數(shù)據(jù)超時(shí)時(shí)長(zhǎng)x秒 val WRITE_TIME_OUT = 30//寫數(shù)據(jù)接超時(shí)時(shí)長(zhǎng)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)) } // 設(shè)置請(qǐng)求頭 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() } }
返回?cái)?shù)據(jù)封裝
class Response<T> { var error: Boolean = false var results: T? = null }
demo中用了gank.io的開發(fā)api,之前一般項(xiàng)目的返回格式是code + message + T的格式。
api接口錯(cuò)誤/異常統(tǒng)一處理類
class ApiException : Exception { var code: Int = 0//錯(cuò)誤碼 var msg: String? = null//錯(cuò)誤信息 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)) } } /** * 錯(cuò)誤/異常處理工具 */ class ExceptionEngine { val UN_KNOWN_ERROR = 1000//未知錯(cuò)誤 val ANALYTIC_SERVER_DATA_ERROR = 1001//解析(服務(wù)器)數(shù)據(jù)錯(cuò)誤 val CONNECT_ERROR = 1002//網(wǎng)絡(luò)連接錯(cuò)誤 val TIME_OUT_ERROR = 1003//網(wǎng)絡(luò)連接超時(shí) fun handleException(e: Throwable): ApiException { val ex: ApiException if (e is ApiException) { //服務(wù)器返回的錯(cuò)誤 return e } else if (e is HttpException) { //HTTP錯(cuò)誤 ex = ApiException(e, e.code()) ex.msg = "網(wǎng)絡(luò)錯(cuò)誤:" + ex.code return ex } else if (e is JsonParseException || e is JSONException || e is ParseException || e is MalformedJsonException) { //解析數(shù)據(jù)錯(cuò)誤 ex = ApiException(e, ANALYTIC_SERVER_DATA_ERROR) ex.msg = "解析錯(cuò)誤" return ex } else if (e is ConnectException) {//連接網(wǎng)絡(luò)錯(cuò)誤 ex = ApiException(e, CONNECT_ERROR) ex.msg = "連接失敗" return ex } else if (e is SocketTimeoutException) {//網(wǎng)絡(luò)超時(shí) ex = ApiException(e, TIME_OUT_ERROR) ex.msg = "網(wǎng)絡(luò)超時(shí)" return ex } else { //未知錯(cuò)誤 ex = ApiException(e, UN_KNOWN_ERROR) ex.msg = e.message return ex } } }
封裝請(qǐng)求處理
object Rx { /** * Rxlifecycle綁定生命周期 */ fun <T, E> get(observable: Observable<Response<T>>, lifecycleProvider: LifecycleProvider<E>): Observable<T> { // 請(qǐng)求綁定生命周期,防止內(nèi)存泄漏,同時(shí)返回回調(diào)之后頁(yè)面已銷毀造成的空指針錯(cuò)誤 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()) } /** * 部分后臺(tái)請(qǐng)求 */ 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, "服務(wù)器異常") // 一般來說,自己的服務(wù)器異常會(huì)返回相應(yīng)的code和message else response.results?.let { subscriber.onNext(response.results!!) } ?: subscriber.onComplete() }) } }
定義HttpObserver統(tǒng)一處理返回
abstract class HttpObserver<T> : Observer<T> { /** * 標(biāo)記是否為特殊情況 */ private var resultNull: Boolean = true override fun onComplete() { // 特殊情況:當(dāng)請(qǐng)求成功,但T == null時(shí)會(huì)跳過onNext,仍需當(dāng)成功處理 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?) /** * 統(tǒng)一處理失敗,比如登錄失效等 * * @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綁定生命周期來處理可能發(fā)生的內(nèi)存泄漏問題,F(xiàn)ragment跟Activity需要繼承Rx相應(yīng)的基類。
練手項(xiàng)目
Meizikt Gank.io Android客戶端,使用Kotlin + Retrofit2 + RxJava
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。