Kotlin 1.3 Coroutines+Retrofit+Okhttp使用

Kotlin 1.3 RC out

2018.9.20 日,kotlin官方宣布1.3RC版本推出了,同时Coroutines将包名中的experimental后缀去掉了,标志着Coroutines library成为了正式版本。我们可以在正式项目中使用coroutines。

Android中使用Kotlin 1.3配置

KotlinConf 2018 Announcements中详细说明了如何配置1.3的使用环境,如下:

Kotlin 1.3 hits RC
Version 1.3 hits RC and brings a ton of new features and functionality.
How to try it
In Maven/Gradle: Add https://dl.bintray.com/kotlin/kotlin-eap as a repository for the build script and your projects. Use 1.3.0-rc-57 as the version number for the compiler plugin and the standard library.
In IntelliJ IDEA: Go to Tools → Kotlin → Configure Kotlin Plugin Updates, select “Early Access Preview 1.3” in the Update channel drop-down list, and then click Check for updates.
The command-line compiler can be downloaded from the Github release page.
On try.kotlinlang.org: Use the drop-down list in the bottom right-hand corner to change the compiler version to 1.3‑RC
Check out the recent blog post on 1.3 RC for more information.

Coroutines VS Rxjava

在如今的Android项目中,Rxjava+Retrofit+Okhttp似乎已经成为标配了,各种异步操作、数据流、http请求返回的数据的处理都使用Rxjava来处理了,非常的方便。虽然Rxjava有非常多的优点,但是,不可能没有缺点。Kotlin coroutines vs RxJava: an initial performance test对coroutines 和 RxJava做了一个测试。
在使用coroutines的时候有一个很棒的地方就是可以把异步代码写成同步代码的方式。
比如简单的获取天气的方法:
RxJava:

   HttpRepository.getWeather
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer(){
            @Override
            public void accept(Weather weather) {
            //update ui
                 showWeather(weather)
            }
        }, new Consumer(){
            @Override
            public void accept(Throwable throwable) {
              
            }
        });

Coroutines:

  try {
            launch {
                val weather = async(IO) { HttpRepository.getWeather() }.await()
                withContext(Dispatchers.Main) {
                    //update ui
                     showWeather(weather)
                }
            }
        } catch (e: Exception) {

        }

上面的两种方式很明显Coroutines的方式简洁,没有了回调,可读性高。

Coroutines+Retrofit+Okhttp使用

和使用RxJava的方式差不多,使用coroutine时,Retrofit的实例:

object HttpRepository {
    private fun getApiService(): Api {
        return Retrofit.Builder()
                .baseUrl("https://raw.githubusercontent.com/")
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .client(provideOkHttpClient(provideLoggingInterceptor()))
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
                .build()
                .create(Api::class.java)
    }

    private fun provideOkHttpClient(interceptor: HttpLoggingInterceptor): OkHttpClient = OkHttpClient.Builder().apply { addInterceptor(interceptor) }.build()

    private fun provideLoggingInterceptor(): HttpLoggingInterceptor = HttpLoggingInterceptor()
            .apply { level = HttpLoggingInterceptor.Level.BODY }

    fun getWeather() = getApiService().getWeather()

}

Api class:

interface Api {
    @GET("zaihuishou/Kotlin-mvvm/master/data.json")
    fun getWeather(): Deferred
}

上面的代码中的 CoroutineCallAdapterFactory是# JakeWharton大神写的一个adapter,使用了这个adapter后,在Api class中定义接口的时候就可以使用Deferred这里类了。经过简单的修改后,coroutine就替换了RxJava了。
Kotlin-Coroutine-Sample,一个包含上述代码的例子

你可能感兴趣的:(Kotlin 1.3 Coroutines+Retrofit+Okhttp使用)