Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom types for Retrofit @Query parameters?

Given the following Retrofit interface:

@GET("offices")
fun getOffices(@Query("uid") uid: String,
               @Query("lat") latitude: Double,
               @Query("lon") longitude: Double
): Call<List<Office>>

How can I replace the location parameters with a more user friendly GeoLocation type ...

data class GeoLocation(
        val latitude: Double,
        val longitude: Double
)

... which is automatically converted to lat and lon at request time such as:

@GET("offices")
fun getOffices(@Query("uid") uid: String,
               @Query("location") location: GeoLocation
): Call<List<Office>>

Here is the Retrofit setup:

fun createRetrofit(baseUrl: String,
                   okHttpClient: OkHttpClient): Retrofit {
    val moshi = Moshi.Builder()
            .build()

    return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .client(okHttpClient)
            .build()
}
like image 647
JJD Avatar asked Aug 01 '17 22:08

JJD


People also ask

What is @query in retrofit Android?

Retrofit uses @Query annotation to define query parameters for requests. Query parameters are defined before method parameters. In annotation, we pass the query parameter name which will be appended in the URL.


1 Answers

If userfriendly access is your concern, you could just create a wrapper function. This way you don't have to mess with your Retrofit configuration at all

fun getOffices(uid: String, location: GeoLocation): Call<List<Office>> {
    return getOfficesIf(uid, location.lat, location.lon)
}

@GET("offices")
fun getOfficesIf(@Query("uid") uid: String,
                 @Query("lat") latitude: Double,
                 @Query("lon") longitude: Double
): Call<List<Office>>
like image 103
Looki Avatar answered Sep 23 '22 04:09

Looki