Retrofit, request get with not-necessary parameters

Viewed 116
2 Answers

Add your query/filter as per you need

val hashMap = HashMap<String, String>()
            hashMap.put("employment", "full_time")
            hashMap.put("time", "7")
            hashMap.put("house", "0")
            hashMap.put("sort", "name")

suppose you do not need house and sort filter then you don't need to put them on hashmap

like,

val hashMap = HashMap<String, String>()
            hashMap.put("employment", "full_time")
            hashMap.put("time", "7")

then calling your api

apiService.getVacanciesWithFilter(hashMap)

In your API service class

@GET("user_vacancy")
    fun getVacanciesWithFilter(
        @QueryMap hashMap: Map<String, String>
    ): Single<VacanciesListResponse>

You don't have to write separate code for each query parameter. Retrofit supports optional query parameters. Here is the Java code for your example. If you pass null for any parameter, Retrofit will omit that query while forming the request.

@GET("user_vacancy") Single<VacanciesListResponse> getVacanciesWithFilter(
    @Query("employment") String employmentType, 
    @Query("time") int time
);

More info here. Using QueryMap is also a good approach as mentioned in another answer.

Related