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

來源:互聯網
上載者:User

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

作者: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 import6     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): Call14 15     @GET("/2.0/?method=album.getInfo")16     fun requestAlbum(@Query("mbid") id: String): Call17 }

 

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

 

 

在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.NONE6     })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中使用,毫無問題

 

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

 

準備好學習如何建立你的第一個項目,就去閱讀免費指南,或者從頭學習如何建立一個完整的應用程式,就直接擷取這本書。

 

 

 

 

 

 

  

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.