在kotlin中使用retrofit+rxjava2

xiaoxiao2021-02-28  164

首先创建个retrofit的单列

/** * Created by JokAr on 2017/6/5. */ class NetworkConfig private constructor() { private val DEFAULT_TIMEOUT: Long = 15 private val BASE_URL: String = "http://gank.io/api" var retrofit: Retrofit = initRetrofit() private object Holder { val INSTANCE = NetworkConfig() } companion object{ val instance:NetworkConfig by lazy { Holder.INSTANCE } } private fun initRetrofit(): Retrofit { val interceptor = HttpLoggingInterceptor() if (BuildConfig.DEBUG) interceptor.setLevel(HttpLoggingInterceptor.Level.BODY) else interceptor.setLevel(HttpLoggingInterceptor.Level.NONE) val client = OkHttpClient.Builder() .addInterceptor(interceptor) .retryOnConnectionFailure(true) .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .build() return Retrofit.Builder() .baseUrl(BASE_URL + "/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() } }

然后创建请求service

/** * Created by JokAr on 2017/6/5. */ interface DataService { @GET("data/{type}/{count}/{pageSize}") fun getData(@Path("type") type: String, @Path("count") count: Int, @Path("pageSize") pageSize: Int) : Observable<HttpResult<ArrayList<DataEntities>>> }

其中HttpResult和DataEntities元素类为

/** * Created by JokAr on 2017/6/5. */ data class DataEntities(@SerializedName("_id") var _id: String, @SerializedName("createdAt") var createdAt: String, @SerializedName("desc") var desc: String, @SerializedName("publishedAt") var publishedAt: String, @SerializedName("source") var source: String, @SerializedName("type") var type: String, @SerializedName("url") var url: String, @SerializedName("used") var used: Boolean, @SerializedName("who") var who: String) : Parcelable { companion object { @JvmField val CREATOR: Parcelable.Creator<DataEntities> = object : Parcelable.Creator<DataEntities> { override fun createFromParcel(source: Parcel): DataEntities = DataEntities(source) override fun newArray(size: Int): Array<DataEntities?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), 1 == source.readInt(), source.readString() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(_id) dest.writeString(createdAt) dest.writeString(desc) dest.writeString(publishedAt) dest.writeString(source) dest.writeString(type) dest.writeString(url) dest.writeInt((if (used) 1 else 0)) dest.writeString(who) } } /** * Created by JokAr on 2017/6/5. */ data class HttpResult<T>(@SerializedName("error") var error: Boolean, @SerializedName("results") var results: T?)

然后就是使用方法了

NetworkConfig.instance .retrofit .create(DataService::class.java) .getData("Android", 10, 1) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .map(HttpResultFunc()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ result -> Log.d("Kotlin", result.toString()) }, { error -> error.printStackTrace() }, { Log.d("Kotlin", "onComplete") }, { Log.d("Kotlin", "onStart") })

其中HttpResultFunc为:

/** * Created by JokAr on 2017/6/5. */ class HttpResultFunc<T> :Function<HttpResult<T>,T> { override fun apply(tHttpResult: HttpResult<T>?): T { if (tHttpResult != null) { if (tHttpResult?.error) { throw APIException() } } return tHttpResult?.results as T } }

END

到此就结束了,跟在java中使用没多大区别,就只是在最后的subscribe有点区别,在代码中已注明

转载请注明原文地址: https://www.6miu.com/read-32233.html

最新回复(0)