Java – multiple similar requests issued in sequence in the transformation

Is there a way to execute multiple requests sequentially in retrofit?

These requests use the same java interface and differ only from the parameters contained in the ArrayList

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

>Click A1,

Call 2. Onresponse() of A1

>Click A2,

Call A2's 2. Onresponse()

>Click A3

.

.

.

.

. an's onresponse() is called

resolvent:

Using rxjava can easily solve the problem

If you have an improved API class, return complete:


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

You can then do 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 transformation API does not return completable, change API. Getuser (it) to API. Getuser (it). Tocompleteable()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>