On Android, how does one use adfit (KAD21) and kotlinw.fit together with Kotlin?
By Antonio Leiva
Time: Apr 18,201 7
Link: https://antonioleiva.com/retrofit-android-kotlin/
This is another example of how to use the same library used by Java in Kotlin.
RetrofitIs a library, which greatly simplifies the request APIIn this example, I plan to teach you how to integrate it with some LastFM API requests. You can read all the code running in the Bandhook Kotlin database.
Duplicate fit 2 in Kotlin
The Kotlin code is very similar to what we use in Java. We will see what are the differences between more details, and you will find that all these are simple and intuitive.
You will also see that we will also create some very practical extension functions.
Build. gradle
I won't explain much here, but you need to add the following command 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 import6 exclude module: 'okhttp'7 }
The first dependency includes the final version of OkHttp and the log record interceptor, which can be used for debugging.
Then we add Retrofit (excluding OkHttp, so that we can control our practical version) and Gson converter converts the request to the class.
Create Communication Interface
This is the central nervous part of fit. This is the request structure you specified.
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 }
It is very simple.It uses symbols to identify the request type, and then the request parameters are used as the parameter functions..
In fit 2, we need to return the type of the called object.
Communication Service Initialization
First, you can initialize the 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.NONE6 })7 .build()8 }
Here we can see the use of the apple function, which will help us initialize the interceptor in the builder style, without any type for the class implementation builder.
LastFmRequestInterceptorNothing, but you can find it on GitHub. The creation of the server in Java is somewhat different:
val retrofit = Retrofit.Builder() .baseUrl("http://ws.audioscrobbler.com") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build()val lastFmService = retrofit.create(LastFmService::class.java)
Create your first request
Because you need to call Retrofit 2, it becomes a bit 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 can create a function in Call to 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 an extensionCallClass. It will execute the request and extractbodySo that it (it will be U type) executes the function f ().
In the above example,TYesLastFmResponse,UYesList.
Conclusion
In this example, I want to show you againAnything you know and likeJavaBoth databases can be stored in KotlinNo problem.
This not only makes things more complex, but simplifies the language code in most cases.
If you are ready to learn how to build your first project, read the free guide, or learn how to create a complete application from scratch to get this book directly.