TheMeanPanda
TheMeanPanda

Reputation: 5

Java Retrofit multiple request one single response

Hello guys I have an api endpoint that only takes one parameter "name": https://api.xxxxx.com/v1/test/{name}/

I'm stuck on making a multiple request (e.g. https://api.xxxxx.com/v1/test/ALEX/ , https://api.xxxxx.com/v1/test/ELISA/, https://api.xxxxx.com/v1/test/JOE/ )

I need to parse all the data from those 3 calls in a recyclerview, each request in a different row.

Is there anyway I can make the 3 request then get 1 JSON response only so I can parse it? What would be the best approach to accomplish this?

Upvotes: 0

Views: 3427

Answers (2)

Lukasz
Lukasz

Reputation: 2317

I assume you have something like the following code in your retrofit api interface

@GET("v1/test/{name}/")
Observable<UserModel> getUserBy(@Path("name") name) 

Then in your business logic you can call.

Observable.zip(retrofitApi.getUser("ALEX"), retrofitApi.getUser("ELISA"), retrofitApi.getUser("JOE"), (u1, u2, u3) -> {
  // prepare your returned users in a way suitable for further consumption
  // in this case I put them in a list
  return Arrays.asList(u1, u2, u3);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe( listOfUsers -> // TODO: do something with your users)

Hope this helps.

Upvotes: 3

Felhi Abdelhafidh
Felhi Abdelhafidh

Reputation: 478

create an Interface like this

@FormUrlEncoded
@POST("/locations/add.json")
void sendMultipleLocations(@Query("token")String token, @FieldMap List<Map<String, String>> multipleLocations, Callback<String> callback);

and use enqueue method of retrofit2 for asynchronously calling multiple request at the same time.This link will help you

https://github.com/square/retrofit/issues/1517

Upvotes: 0

Related Questions