在Android上,怎樣與Kotlin一起使用Retrofit(KAD21)


作者:Antonio Leiva

時間:Apr 18, 2017

原文鏈接:https://antonioleiva.com/retrofit-android-kotlin/

 

 

這是又一個例子,關於怎樣在Kotlin中使用Java使用過的相同庫。

 

 

Retrofit是一個庫,它極大地簡化了請求API,在這個例子中我計划教你怎樣將其與一些LastFM API請求集成。你能夠讀到運行在Bandhook Kotlin創庫全部代碼。

 

 

Kotlin中的Retrofit 2

 

Kotlin代碼是非常類似我們在Java中用的。我們將看到更多的細節有哪些不同,而且,你會發現這一切都是很簡單和直觀的。

 

你還會看到我們也將創建一些非常實用的擴展函數。

 

 

構建build.gradle

 

我在這里不會解釋太多,而你需要將下面指令加入到build.gradle中:

1 compile "com.squareup.okhttp3:okhttp:$okhttpVersion"
2 compile "com.squareup.okhttp3:logging-interceptor:$okhttpVersion"
3 
4 compile ("com.squareup.retrofit2:retrofit:$retrofitVersion"){
5     // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
6     exclude module: 'okhttp'
7 }

 

第一個依賴關系包括OkHttp最后的版本和日志記錄攔截器,它能夠用於調試。

 

接着加Retrofit(不包括OkHttp,這樣我們控制我們實用的版本),Gson轉換器轉換請求給類。

 

創建通訊接口

 

 

這是Retrofit的中樞神經部分。這是你指定的請求結構,將需要匹配的API

 1 interface LastFmService {
 2 
 3     @GET("/2.0/?method=artist.search")
 4     fun searchArtist(@Query("artist") artist: String): Call
 5 
 6     @GET("/2.0/?method=artist.getinfo")
 7     fun requestArtistInfo(@Query("mbid") id: String, @Query("lang") language: String): Call
 8 
 9     @GET("/2.0/?method=artist.gettopalbums")
10     fun requestAlbums(@Query("mbid") id: String, @Query("artist") artist: String): Call;
11 
12     @GET("/2.0/?method=artist.getsimilar")
13     fun requestSimilar(@Query("mbid") id: String): Call
14 
15     @GET("/2.0/?method=album.getInfo")
16     fun requestAlbum(@Query("mbid") id: String): Call
17 }

 

它十分簡單。它用符號標識請求的類型,然后請求的參數作為參數的函數

 

 

Retrofit 2中,我們需要返回調用對象類型。

 

通訊服務的初始化

 

 

首先,你能夠按如下初始化OkHttp client端:

1 val client = OkHttpClient().newBuilder()
2     .cache(cache)
3     .addInterceptor(LastFmRequestInterceptor(apiKey, cacheDuration))
4     .addInterceptor(HttpLoggingInterceptor().apply {
5         level = if (BuildConfig.DEBUG) Level.BODY else Level.NONE
6     })
7     .build()
8 }

 

這里我們看到了apple函數的使用,它將幫助我們以構建者風格初始化攔截器,不需要為類實現構建者的任何類型。

 

LastFmRequestInterceptor沒有什么了不起,但是你能夠到GitHub上找到。服務器端的創建於Java有些不同:

val retrofit = Retrofit.Builder()
        .baseUrl("http://ws.audioscrobbler.com")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

val lastFmService = retrofit.create(LastFmService::class.java)

 

建立你的第一個請求

 

 

由於需要調用Retrofit 2,它成為一點冗余代碼:

1 val call = lastFmService.requestAlbums(mbid, name)
2 val result = call.execute().body()
3 val albums = AlbumMapper().transform(result.topAlbums.albums)

 

然而,幸虧有擴展函數,我們能夠在Call創建一個函數,提取值,就如同這樣:

1 val albums = lastFmService.requestAlbums(mbid, name).unwrapCall { 
2     AlbumMapper().transform(topAlbums.albums)
3 }

 

非常簡單,對面?

 

 

unwrapCall的格式是什么?

1 inline fun <T, U> Call.unwrapCall(f: T.() -> U): U = execute().body().f()

 

它是擴展Call類的函數。它將執行請求,提取body,使其(它將是U類型)執行函數f()

 

在上面例子中,TLastFmResponseUList

 

 

結論

 

 

用這個例子,我想要向你再次展示任何你知道的,且喜歡的Java庫都能夠在Kotlin中使用,毫無問題

 

這非但沒有使事情變得更復雜,而是在大多數情況下,簡化語言代碼。

 

准備好學習如何建立你的第一個項目,就去閱讀免費,或者從頭學習如何創建一個完整的應用程序,就直接獲取這本書

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM