How to use custom types for Retrofit @Query parameters?

Viewed 10230

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()
}
2 Answers

You can use Query in suspend function as a parameter like that:

@GET("Posts")
suspend fun getPosts(@Query("MaxCount") maxCount: Int): Response<Posts>
Related