如果我有使用改造的4 api服务请求并且我在我的活动中调用所有这些请求,请执行第二个等待第一个完成或第二个或第三个请求而不等待其他完成,这里myapi服务列表:
@FormUrlEncoded
@POST("goes/for/api1")
Observable<ResponseBody> req1(
@HeaderMap Map<String, String> headers,
@FieldMap Map<String, String> fields);
@FormUrlEncoded
@POST("goes/for/api2")
Observable<ResponseBody> req2(
@HeaderMap Map<String, String> headers,
@FieldMap Map<String, String> fields);
@FormUrlEncoded
@POST("goes/for/api3")
Observable<ResponseBody> req3(
@HeaderMap Map<String, String> headers,
@FieldMap Map<String, String> fields);
@FormUrlEncoded
@POST("goes/for/api4")
Observable<ResponseBody> req4(
@HeaderMap Map<String, String> headers,
@FieldMap Map<String, String> fields);
主持人请求:
public void request1(){
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
Map<String, String> fields = new HashMap<>();
fields.put("key", "value");
Observable<ResponseBody> response = mApiService.req1(headers, fields);
subscribe(response, this);
}
public void request2(){
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
Map<String, String> fields = new HashMap<>();
fields.put("key", "value");
Observable<ResponseBody> response = mApiService.req2(headers, fields);
subscribe(response, this);
}
public void request3(){
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
Map<String, String> fields = new HashMap<>();
fields.put("key", "value");
Observable<ResponseBody> response = mApiService.req3(headers, fields);
subscribe(response, this);
}
public void request4(){
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
Map<String, String> fields = new HashMap<>();
fields.put("key", "value");
Observable<ResponseBody> response = mApiService.req4(headers, fields);
subscribe(response, this);
}
我的演示者处理并传递对活动的响应
@Override
public void onNext(ResponseBody responseBody) {
try {
getView().onDeliverResponse(responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
每次打电话我都会提出状态请求String state = "state1"
@Override
public void onDeliverResponse(String response) {
handleResponse(response);
}
void handleResponse(String response) {
if(state = "state1"){
//
}
else {
//
}
}
我的状态字符串将覆盖到我的上一个请求"state4"
,所以当第3个请求完成时状态变为“state4”?每个请求都会更新我的ui
问题是,当您相互分别调用这些API请求时,您永远不会知道OnNext方法调用的顺序,因为它取决于服务器响应时间。例如。你可以按顺序调用这些请求
REQ1
REQ2
别别扭扭
REQ4
但得到像这样的州
resp2
resp4
resp1
resp3
所以,你的最终状态将是state3。如果要按顺序获得响应,则应使用RxJava运算符,例如flatMap或其他运算符:
apiService.A()
.doOnNext(modelA -> getView().updateState("state1"))
.flatMap(modelA -> apiService.B())
.doOnNext(modelb -> getView().updateState("state2"));
示例:https://medium.com/@adinugroho/chaining-multiple-retrofit-call-using-rxjava-177b64c8103e
或者在之前的可观察订阅的onNext(或onCompleted)中调用每个observable。