Coroutines+Retrofit实现网络请求

简要介绍

Retrofit是当前应用非常广泛的网络请求框架,而Coroutines则是Kotlin中用于执行异步任务的框架,比RxJava还要方便易用,本文将展示一个采用Coroutines+Retrofit的网络请求demo. 若想了解RxJava+Retrofit,可参考《RxJava+Retrofit实现网络请求》

集成步骤

  1. app工程的build.gradle中添加依赖
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
    implementation "com.squareup.retrofit2:retrofit:2.6.0"
    implementation "com.squareup.retrofit2:converter-gson:2.6.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.11.0"
    implementation "com.squareup.okhttp3:okhttp:3.14.2"
  1. 在AndroidManifest.xml中添加权限

  1. 添加数据类Task
    data class Task(var id: Int, var name: String?)
  2. 添加网络请求类NetworkService
interface NetworkService {
    @GET("cxyzy1/coroutineRetrofitDemo/raw/master/data.json")
    suspend fun query(): Task
}
  1. activity中调用
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        queryData()
    }

    private fun queryData() {
        val okHttpClient = OkHttpClient.Builder()
                .apply {
                    addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY })
                }.build()
        val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl("https://gitee.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        val networkService = retrofit.create(NetworkService::class.java)
        GlobalScope.launch(Dispatchers.Main) {
            val result = withContext(Dispatchers.IO) { networkService.query() }
            contentTv.text = result.toString()
        }
    }
}

网络请求结果截图

Coroutines+Retrofit实现网络请求_第1张图片

Demo源代码

https://gitee.com/cxyzy1/coroutineRetrofitDemo/tree/master/app

安卓开发技术分享: https://www.jianshu.com/p/442339952f26
点击关注专辑,查看最新技术分享
更多技术总结好文,请关注:「程序园中猿」

Coroutines+Retrofit实现网络请求_第2张图片

你可能感兴趣的:(Coroutines+Retrofit实现网络请求)