189 8069 5689

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 (lifecycleProvider 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


网页标题:Kotlin+Retrofit+RxJava简单封装使用详解
网页URL:http://jkwzsj.com/article/gijodd.html

其他资讯