1. 程式人生 > >How to use Retrofit on android with Kotlin (KAD 21)

How to use Retrofit on android with Kotlin (KAD 21)

This is just one more example about how in Kotlin we can continue to use the same libraries we’ve always used in Java for Android.

Retrofit is a library that greatly simplifies doing requests to an API, and in this case I’m going to teach you how to integrate it with some LastFM API requests. You can see the full code working in the

Bandhook Kotlin repository.

Retrofit 2 in Kotlin

The code in Kotlin is going to be very similar to what we would use in Java. We’ll see more in detail what are some of their differences, but you’ll see that everything is pretty easy and intuitive.

And we’ll also create some very useful extension functions, you’ll see.

Build the build.gradle

I won’t stop here too much, but you need to add the following instructions to build.gradle:

12345678 compile"com.squareup.okhttp3:okhttp:$okhttpVersion"compile"com.squareup.okhttp3:logging-interceptor:$okhttpVersion"compile("com.squareup.retrofit2:retrofit:$retrofitVersion"){// exclude Retrofit’s OkHttp peer-dependency module and define your own module importexclude module:'okhttp'}compile"com.squareup.retrofit2:converter-gson:$retrofitVersion"

The first dependencies include the latest version of OkHttp and a logging interceptor, which can be useful for debugging.

The following add Retrofit (excluding OkHttp, so we have control over the version we use), and the Gson converter to convert requests to classes.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

Create the communication interface

This is the neuralgic part of Retrofit. It’s where you specify the structure of the requests, which will have to match the API:

1234567891011121314151617 interfaceLastFmService{@GET("/2.0/?method=artist.search")fun searchArtist(@Query("artist")artist:String):Call@GET("/2.0/?method=artist.getinfo")fun requestArtistInfo(@Query("mbid")id:String,@Query("lang")language:String):Call@GET("/2.0/?method=artist.gettopalbums")fun requestAlbums(@Query("mbid")id:String,@Query("artist")artist:String):Call;@GET("/2.0/?method=artist.getsimilar")fun requestSimilar(@Query("mbid")id:String):Call@GET("/2.0/?method=album.getInfo")fun requestAlbum(@Query("mbid")id:String):Call}

It’s quite simple. It identifies the type of the request with the notation, and then the parameters of the request as arguments of the function.

In Retrofit 2, we need to return objects of type Call.

Initialization of the communication service

First you can initialize the OkHttp client as follows:

12345678 val client=OkHttpClient().newBuilder().cache(cache).addInterceptor(LastFmRequestInterceptor(apiKey,cacheDuration)).addInterceptor(HttpLoggingInterceptor().apply{level=if(BuildConfig.DEBUG)Level.BODY elseLevel.NONE}).build()}

Here we can see the use of the function, apply, which will help us initialize the interceptor in the style of a builder, without the need for the class to implement any type of builder.

The LastFmRequestInterceptor has nothing remarkable, but you can take a look on Github. The creation of the service has nothing different to Java:

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

Make your first request

Due to the need for Call in Retrofit 2, it becomes a bit more tedious code:

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

However, thanks to the extension functions, we can create a function on Call to retrieve the values, like this:

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

Much simpler, right?

What is the form of unwrapCall?

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

It’s a function that extends Call class. It will execute the request, retrieve the body, and make this one (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 wanted to show you once again that any of the Java libraries you know and love can be used in Kotlin without issues.

Also, far from making things more complicated, in most cases the language will simplify the code.

Get ready and take a look at the free guide to learn how to build your first project, or just get the book and learn how to create a complete App from scratch.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

How to use Retrofit on android with Kotlin (KAD 21)

This is just one more example about how in Kotlin we can continue to use the same libraries we’ve always used in Java for Android. Retrofit is a libr

How to use Dagger 2 on Android with Kotlin (KAD 20)

Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later. Although there is some

How to make unit test on Android with Kotlin (KAD 22)

Of course, Kotlin also allows us to do unit tests in a very simple way, and very similar to what we’re used in Java. There are some small complicatio

How To Use Retrofit Library In Your Android App

Retrofit library is a Type-safe REST client for android and Java, courtesy of Square Inc. Most modern android apps make HTTP requests to some remote s

How to Use vcpkg On Windows

Introduction If you do any sort of C++ development on Windows, then you know that library/package management can be quite a pain at times (ever built Open

How to use Python on microcontrollers for Blockchain and IoT applications

This tutorial will be exploring the potential of combining IoT and blockchain using simple Python directly on microcontrollers, thanks to Zerynth t

Reified Types in Kotlin: how to use the type within a function (KAD 14)

One of the limitations that most frustrates Java developers when using generics is not being able to use the type directly. Normally this is solved b

How to Use Loaders in Android

With the introduction of Honeycomb Loaders became the preferred way to access data of databases or content providers.

Custom Views in Android with Kotlin (KAD 06)

When we saw the article about classes, you may remember that in general only one constructor is used. This is a problem for creating custom views. Th

How to Use an SSL Certificate on ACM or IAM with CloudFront

{ "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Action": [ "acm:ListCertificates",

How to use Kata Containers and CRI (containerd plugin) with Kubernetes

bsp use k8s doc ner blob ber uber net https://github.com/kata-containers/documentation/blob/master/how-to/how-to-use-k8s-with-cri-contain

How to use Toyota simulated card + P001 Programmer with Obdstar X300 DP PLUS

Obdstar X300 DP Plus OBDSTAR X300 DP Plus key programmer OBDSTAR X300 DP plus PAD X300 DP Plus Purpose: To check if OBDSTAR X300 DP PLUS can

How to use for ASP.NET Core with csproj

2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main 2017-10-10 23:40:30.9739|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManageme

How To Handle Network On Main Thread Error In Android

NetworkOnMainThreadException is a pretty popular exception among those new to android development. This exception is mainly thrown whenever an applicati

How to use common workflows on Amazon SageMaker notebook instances

Amazon SageMaker notebook instances provide a scalable cloud based development environment to do data science and machine learning. This blog post

How to Use Local Keywords to Rank Higher on Google

Many strategies can help you rank better for competitive keywords related to your product and industry. However, one often overlooked factor is local SEO.

How to use APIs with Pandas and store the results in Redshift

How to use APIs with Pandas and store the results in RedshiftHere is an easy tutorial to help understand how you can use Pandas to get data from a RESTFUL

How to use ReactJS with Webpack 4, Babel 7, and Material Design

So this is where Babel comes to our aid. Babel will tell Webpack how to compile our React code.Let’s go ahead and add a bunch of Babel packages to our app

How to use Context with Dialogflow to handle errors (Part 2: Knock Knock, It’s me)

How to use Contextual Fallback with Dialogflow to handle errors (Part 2: Knock Knock Jokes)(This is Part 2 of a four-part series on how to use Context with

How to setup ACRA, an Android Application Crash Tracking system, on your own host

One truth about developing a mobile application is there are so many constraints for example, a hardware limitation (CPU, RAM, Battery, e