等待所有请求完成的干净方法是将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
}