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()
}
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.
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>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With