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<Weather>(){
@Override
public void accept(Weather weather) {
//update ui
showWeather(weather)
}
}, new Consumer<Throwable>(){
@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<Weather>
}
上面的代碼中的 CoroutineCallAdapterFactory是# JakeWharton大神寫的一個adapter,使用了這個adapter后,在Api class中定義接口的時候就可以使用Deferred這里類了。經過簡單的修改后,coroutine就替換了RxJava了。
Kotlin-Coroutine-Sample,一個包含上述代碼的例子