Kotlin协程+Retrofit、Gson解析

Kotlin协程+Retrofit、Gson解析

添加依赖

implementation "io.github.cnoke.ktnet:api:?"

添写数据基类

open class ApiResponse(    
    var data: T? = null,  
    var errorCode: String = "",     
    var errorMsg: String = ""
)

实现com.cnoke.net.factory.GsonResponseBodyConverter

class MyGsonResponseBodyConverter : GsonResponseBodyConverter() {     
override fun convert(value: ResponseBody): Any {
         val jsonReader = gson.newJsonReader(value.charStream())
         val data = adapter.read(jsonReader) as ApiResponse<*>
         val t = data.data
         val listData = t as? ApiPagerResponse<*>
         if (listData != null) {
             //如果返回值值列表封装类,且是第一页并且空数据 那么给空异常 让界面显示空
             if (listData.isRefresh() && listData.isEmpty()) {
                 throw ParseException(NetConstant.EMPTY_CODE, data.errorMsg)
             }
         }
         // errCode 不等于 SUCCESS_CODE,抛出异常
         if (data.errorCode != NetConstant.SUCCESS_CODE) {
             throw ParseException(data.errorCode, data.errorMsg)
         }
         return t!!
  } }

进行网络请求

 interface TestServer {
     @GET("banner/json")
     suspend fun awaitBanner(): Await> }
 val okHttpClient = OkHttpClient.Builder()
             .addInterceptor(HeadInterceptor())
             .addInterceptor(LogInterceptor())
             .build()
 val retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("https://www.wanandroid.com/")
						.addCallAdapterFactory(ApiResultCallAdapterFactory())
						.addConverterFactory(GsonConverterFactory.create(ApiResponse::class.java,MyGsonResponseBodyConverter()))                       
						.build()
 val service: TestServer = retrofit.create(TestServer::class.java)
 lifecycleScope.launch {
        val banner = service.awaitBanner().await()
} 

异步请求、同步请求

fun banner(){
    lifecycleScope.launch {
        //单独处理异常 tryAwait会处理异常,如果异常返回空
        val awaitBanner = service.awaitBanner().tryAwait()
        awaitBanner?.let {
            for(banner in it){
                Log.e("awaitBanner",banner.title)
            }
        }

        /**
         * 不处理异常 异常会直接抛出,统一处理
         */
        val awaitBannerError = service.awaitBanner().await()
    }
}

/**
 * 串行 await
 */
fun serial(){
    lifecycleScope.launch {
        //先调用第一个接口await
        val awaitBanner1 = service.awaitBanner().await()
        //第一个接口完成后调用第二个接口
        val awaitBanner2 = service.awaitBanner().await()
    }
}

/**
 * 并行 async
 */
fun parallel(){
    lifecycleScope.launch {
        val awaitBanner1 = service.awaitBanner().async(this)
        val awaitBanner2 = service.awaitBanner().async(this)

        //两个接口一起调用
        awaitBanner1.await()
        awaitBanner2.await()
    }
}

协程+OKHttp

加入依赖

//使用kotlin的依赖
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.71"

//在Android中使用协程需要添加此依赖
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'

初始化OkHttpClient

private lateinit var client: OkHttpClient
private lateinit var builder: OkHttpClient.Builder

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreat

你可能感兴趣的:(android,kotlin)