Authors: Antonio Leiva
Time: Apr 18, 2017
Link to the original text: https://antonioleiva.com/retrofit-android-kotlin/
This is another example of how to use the same library Java used in Kotlin.
Retrofit is a library that greatly simplifies the request API. In this example, I plan to teach you how to integrate it with some LastFM API requests. You can read that running in Bandhook Kotlin Create all the code.
Retrofit 2 in Kotlin
Kotlin code is very similar to what we use in Java. We'll see more details about what's different, and you'll find that it's all very simple and intuitive.
You will also see that we will also create some very useful extension functions.
Build build.gradle
I won't explain much here, but you need to add the following instructions to 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 }
The first dependency includes the final version of OkHttp and the log interceptor, which can be used for debugging.
Then add Retrofit (excluding OkHttp, so that we control our practical version), and the Gson converter converts the request to the class.
Create a communication interface
This is the central nervous system of Retrofit. This is the request structure you specify and will need to match the 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 }
It's very simple. It uses symbols to identify the type of request, and then the parameters of the request are used as functions of the parameters.
In Retrofit 2, we need to return the call object type.
Initialization of communication services
First, you can initialize OkHttp client as follows:
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 }
Here we see the use of the apple function, which will help us initialize the interceptor in the builder's style without implementing any type of builder for the class.
LastFmRequest Interceptor is no big deal, but you can Find it on GitHub . Server-side creation is somewhat different from Java:
val retrofit = Retrofit.Builder() .baseUrl("http://ws.audioscrobbler.com") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() val lastFmService = retrofit.create(LastFmService::class.java)
Establish your first request
Because Retrofit 2 needs to be called, it becomes a little redundant code:
1 val call = lastFmService.requestAlbums(mbid, name) 2 val result = call.execute().body() 3 val albums = AlbumMapper().transform(result.topAlbums.albums)
However, thanks to the extension function, we were able to create a function in Call and extract values, just like this:
1 val albums = lastFmService.requestAlbums(mbid, name).unwrapCall { 2 AlbumMapper().transform(topAlbums.albums) 3 }
Very simple, opposite?
What is the format of unwrapCall?
1 inline fun <T, U> Call.unwrapCall(f: T.() -> U): U = execute().body().f()
It is a function that extends the Call class. It will execute the request, extract the body, and make it (which will be of type U) execute the function f().
In the above example, T is LastFmResponse and U is List.
conclusion
With this example, I want to show you once again that any Java library you know and like can be used in Kotlin, no problem.
Not only does this not make things more complicated, it simplifies language code in most cases.
Ready to learn how to build your first project, read Free Guide Or learn from scratch how to create a complete application, directly Get the book.