改造中依次有多个类似的请求

Mal*_*ngh 5 java android kotlin retrofit retrofit2

在Retrofit中,有什么方法可以依次执行多个请求吗?

这些请求使用相同的Java接口,只是它们所包含的参数有所不同ArrayList

对于请求A1,A2,A3,A4,A5 ...

  1. 打A1

onResponse()A1的2 。

  1. 打A2

2. onResponse()A2中的称为

  1. 打A3。

onResponse()被称为。

azi*_*ian 4

使用RxJava可以轻松解决该问题。

假设您有一个改造Api类,它返回Completable


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

然后你可以执行以下操作:


    // 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) })

如果您的改造 API 未返回 a Completable,则更api.getUser(it)改为api.getUser(it).toCompletable().