美文网首页安卓开发android开发技巧
安卓Coroutines结合Retrofit发送单个或多个网络请

安卓Coroutines结合Retrofit发送单个或多个网络请

作者: 蓝不蓝编程 | 来源:发表于2020-05-12 10:59 被阅读0次

    目标

    采用Coroutines结合Retrofit,发送单个或多个网络请求(串行),并更新UI.

    实现方案

    发送单个网络请求方案

    1. 修改app工程的build.gradle文件
    • 在android节点下添加如下信息
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    
    • 添加依赖
    implementation 'com.squareup.retrofit2:retrofit:2.7.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
    
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
    
    1. 定义数据类Task.kt
    data class Task(val id: Int, var name: String)
    
    1. 创建网络接口类NetworkService.kt
    interface NetworkService {
        @GET("cxyzy1/AndroidAsyncTaskDemo/raw/master/data.json")
        suspend fun query(): Task
    }
    
    1. 创建网络工具类NetworkUtils.kt
    fun getNetworkService(): NetworkService {
        val okHttpClient = OkHttpClient.Builder().build()
        val retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("https://gitee.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    
        return retrofit.create(NetworkService::class.java)
    }
    
    1. activity调用
    private fun queryData() {
        val networkService = getNetworkService()
        GlobalScope.launch(Dispatchers.Main) {
            val result = withContext(Dispatchers.IO) { networkService.query() }
            contentTv.text = result.toString()
        }
    }
    

    发送两个网络请求方案

    1. 修改app工程的build.gradle文件,同上
    2. 定义数据类Task.kt,同上
    3. 创建网络接口类NetworkService.kt
    interface NetworkService {
        @GET("cxyzy1/AndroidAsyncTaskDemo/raw/master/data.json")
        suspend fun query(): Task
    
        @GET("cxyzy1/AndroidAsyncTaskDemo/raw/master/data2.json")
        suspend fun query2(): Task
    }
    
    1. 创建网络工具类NetworkUtils.kt,同上
    2. activity调用
    private fun queryData() {
        val networkService = getNetworkService()
        GlobalScope.launch(Dispatchers.Main) {
            val result = withContext(Dispatchers.IO) { networkService.query() }
            contentTv.text = result.name
    
            val result2 = withContext(Dispatchers.IO) { networkService.query2() }
            contentTv2.text = result2.name
        }
    }
    

    代码说明:
    直接顺序调用query和query2两个接口.

    完整源代码

    https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/tree/master/coroutinesDemo

    相关文章

      网友评论

        本文标题:安卓Coroutines结合Retrofit发送单个或多个网络请

        本文链接:https://www.haomeiwen.com/subject/ulavnhtx.html