gpt4 book ai didi

java - 改造中的多个相似请求顺序

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:51:35 25 4
gpt4 key购买 nike

Retrofit中有没有什么方法可以顺序执行多个请求?

这些请求使用相同的 Java 接口(interface),只是它们采用的参数不同,这些参数包含在 ArrayList 中。

对于请求A1、A2、A3、A4、A5……一个

  1. 点击A1,

  2. A1的onResponse()被调用

  3. 点击A2,

  4. A2的onResponse()被调用

  5. 点击 A3.

.

.

.

.

.调用 An 的 onResponse()

最佳答案

这个问题可以用RxJava轻松解决.

假设您有一个 retrofit 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 未返回 Completable,则将 api.getUser(it) 更改为 api.getUser(it).toCompletable().

关于java - 改造中的多个相似请求顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44800204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com