Android uses Kotlin coroutines to encapsulate network libraries

Overview

         Recently, the network library has to be replaced again, which has caused all business codes to be replaced and re-tested and regression. In order to prevent such things from being encountered in the future, and to reduce the cost of replacing the core library, the network library is now encapsulated using a coroutine.

 

Ideal API call method

     launch {
            val response = TestReq(q = "电脑").request<TestResponse>()
            Toast.makeText(this, response?.result?.toString()?:"网络异常", Toast.LENGTH_SHORT).show()
            }

Request definition

@URL("https://suggest.taobao.com/sug")
@GET
data class TestReq(var code: String = "utf-8", val q: String) : IReq


class TestResponse {
    var result: List<Any>? = null
}

Description

    Launch is a class extension of Context. For Activity, the coroutine can be closed when it is destroyed; other scenarios can manage the coroutine by itself. E.g:

import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() , CoroutineScope by MainScope() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        launch {
            val response = TestReq(q = "电脑").request<TestResponse>()
            Toast.makeText(this@MainActivity, response?.result?.toString()?:"网络异常", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }

}

 

use

Quote

  implementation 'com.zhangzheng.easyhttp:library:1.0.1'

initialization

Default (HttpUrlConnection)

EasyHttp.init(DefaultAdapter(GsonJsonParse()))
 implementation 'com.google.code.gson:gson:2.8.6'

OkHttp

 EasyHttp.init(OKHttpAdapter(GsonJsonParse()))
    implementation 'com.squareup.okhttp3:okhttp:3.8.0'
    implementation 'com.squareup.okio:okio:1.12.0'

 implementation 'com.google.code.gson:gson:2.8.6'

Vollery

EasyHttp.init(VolleyAdapter(this,GsonJsonParse()))
    implementation 'com.android.volley:volley:1.1.1'

 implementation 'com.google.code.gson:gson:2.8.6'

If you are using FastJson, you can replace the parser

GsonJsonParse() --> FastJsonParse()
  implementation 'com.alibaba:fastjson:1.2.37'

If the coroutine is not available, check whether the coroutine library is introduced

 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"

 

Custom extension

        You can extend EasyHttp.IAdapter by yourself, and you only need to develop an adapter for the subsequent replacement of the network request core library. For json parsing, IResponseParse can be implemented to expand. Examples are as follows:

 

IAdapter

class OKHttpAdapter(var parse: IResponseParse) : EasyHttp.IAdapter {
    override suspend fun request(url: String, params: Map<String, String>, isGet: Boolean): String {
        val okHttpClient = OkHttpClient()
        val formBody = FormBody.Builder()
        params.forEach {
            formBody.add(it.key,it.value)
        }

        val request: Request =if(isGet){
             Request.Builder().url(url.urlWithParam(params)).method("GET", null)
        }else{
             Request.Builder().url(url).method("POST", createParamBody(params))
        }.build()

        val call: Call = okHttpClient.newCall(request)
        return call.execute().body()?.string()?:""
    }

    override fun <T> parse(value: String, clazz: Class<T>)=parse.parse(value,clazz)


    private fun createParamBody(params: Map<String, String>):FormBody{
        val formBody = FormBody.Builder()
        params.forEach {
            formBody.add(it.key,it.value)
        }
        return formBody.build()
    }
}

 

IResponseParse

class FastJsonParse :IResponseParse{

    override fun <T > parse(value: String, clazz: Class<T>)=JSON.parseObject(value,clazz)

}

 

github address: https://github.com/long8313002/EasyHttp

Guess you like

Origin blog.csdn.net/long8313002/article/details/108751307