Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple similar requests in sequence in retrofit

Is there any way to execute multiple requests in sequence in Retrofit?

These requests uses same Java interface and differ only by parameters they take which are contained in ArrayList.

For requests A1, A2, A3, A4, A5...... An

  1. Hit A1,

  2. onResponse() of A1 is called

  3. Hit A2,

  4. onResponse() of A2 is called

  5. Hit A3 .

.

.

.

.

. onResponse() of An is called.

like image 696
Malwinder Singh Avatar asked Jun 28 '17 10:06

Malwinder Singh


People also ask

What is @body in retrofit?

An object can be specified for use as an HTTP request body with the @Body annotation. The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.

Is retrofit restful?

Retrofit is a REST Client for Java and Android allowing to retrieve and upload JSON (or other structured data) via a REST based You can configure which converters are used for the data serialization, example GSON for JSON.


1 Answers

The problem can be easily solved with RxJava.

Assuming you have a retrofit Api class, that returns a Completable:


    interface Api {
      @GET(...)
      fun getUser(id: String): Completable
    }

Then you can perform this:


    // Create a stream, that emits each item from the list, in this case "param1" continued with "param2" and then "param3"
    Observable.fromIterable(listOf("param1", "param2", "param3"))
      // we are converting `Observable` stream into `Completable`
      // also we perform request here: first time parameter `it` is equal to "param1", so a request is being made with "param1"
      // execution will halt here until responce is received. If response is successful, only then a call with second param ("param2") will be executed
      // then the same again with "param3"
      .flatMapCompletable { api.getUser(it) }
      // we want request to happen on a background thread
      .subscribeOn(Schedulers.io())
      // we want to be notified about completition on UI thread
      .observeOn(AndroidSchedulers.mainThread())
      // here we'll get notified, that operation has either successfully performed OR failed for some reason (specified by `Throwable it`)
      .subscribe({ println("completed") }, { println(it.message) })

If your retrofit API does not return a Completable, then change api.getUser(it) to api.getUser(it).toCompletable().

like image 181
azizbekian Avatar answered Sep 22 '22 10:09

azizbekian