retrofit 会请求两次_Retrofit2-如何提出多个请求并等待直到数据来自Retrofit 2.0中的所有请求-Android...

等待所有请求完成的干净方法是将Retrofit2与RxJava2及其Kotlin函数结合使用。

Kotlin所做的基本上是构造一个新的可观察的对象,它会等到您所有的Observable089更新请求都完成后再发出自己的结果。

这是带有Observables的Retrofit2接口示例:

public interface MyBackendAPI {

@GET("users/{user}")

Observable getUser(@Path("user") String user);

@GET("users/{user}/photos")

Observable> listPhotos(@Path("user") String user);

@GET("users/{user}/friends")

Observable> listFriends(@Path("user") String user);

}

在将要发出多个请求并且仅在所有请求都完成之后再执行一些操作的代码中,然后可以编写以下内容:

Retrofit retrofit = new Retrofit.Builder()

.baseUrl("https://api.example.com/")

.build();

MyBackendAPI backendApi = retrofit.create(MyBackendAPI.class);

List> requests = new ArrayList<>();

// Make a collection of all requests you need to call at once, there can be any number of requests, not only 3. You can have 2 or 5, or 100.

requests.add(backendApi.getUser("someUserId"));

requests.add(backendApi.listPhotos("someUserId"));

requests.add(backendApi.listFriends("someUserId"));

// Zip all requests with the Function, which will receive the results.

Observable.zip(

requests,

new Function() {

@Override

public Object apply(Object[] objects) throws Exception {

// Objects[] is an array of combined results of completed requests

// do something with those results and emit new event

return new Object();

}

})

// After all requests had been performed the next observer will receive the Object, returned from Function

.subscribe(

// Will be triggered if all requests will end successfully (4xx and 5xx also are successful requests too)

new Consumer() {

@Override

public void accept(Object o) throws Exception {

//Do something on successful completion of all requests

}

},

// Will be triggered if any error during requests will happen

new Consumer() {

@Override

public void accept(Throwable e) throws Exception {

//Do something on error completion of requests

}

}

);

就这样 :)

以防万一想要显示相同的代码在Kotlin中的样子。

val retrofit = Retrofit.Builder()

.baseUrl("https://api.example.com/")

.build()

val backendApi = retrofit.create(MyBackendAPI::class.java)

val requests = ArrayList>()

requests.add(backendApi.getUser())

requests.add(backendApi.listPhotos())

requests.add(backendApi.listFriends())

Observable

.zip(requests) {

// do something with those results and emit new event

Any() //

}

// Will be triggered if all requests will end successfully (4xx and 5xx also are successful requests too)

.subscribe({

//Do something on successful completion of all requests

}) {

//Do something on error completion of requests

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值