如何在Rx Vert.X中结束链接请求?
HttpClient client = Vertx.vertx().createHttpClient();
HttpClientRequest request = client.request(HttpMethod.POST,"someURL")
.putHeader("content-type","application/x-www-form-urlencoded")
.putHeader("content-length",Integer.toString(jsonData.length())).write(jsonData);
request.toObservable().
//flatmap HttpClientResponse -> Observable
请注意,我有顶级请求的.end().如何结束.flatmap内的请求?我甚至需要结束它吗?
最佳答案
我认为你可以做类似下面的代码.
主要思想是您不直接使用Vertx客户端获取的HttpClientRequest.相反,您创建另一个可流动的,一旦收到第一个订阅就会调用end().
例如,您可以通过一对自定义方法获取请求:在本例中为request1()和request2().它们都使用doOnSubscribe()来触发你需要的end(). Read its description on the ReactiveX page.
这个考试使用vertx和reactivex,我希望你可以使用这个设置.
import io.reactivex.Flowable;
import io.vertx.core.http.HttpMethod;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.buffer.Buffer;
import io.vertx.reactivex.core.http.HttpClient;
import io.vertx.reactivex.core.http.HttpClientRequest;
import io.vertx.reactivex.core.http.HttpClientResponse;
import org.junit.Test;
public class StackOverflow {
@Test public void test(){
Buffer jsonData = Buffer.buffer("..."); // the json data.
HttpClient client = Vertx.vertx().createHttpClient(); // the vertx client.
request1(client)
.flatMap(httpClientResponse -> httpClientResponse.toFlowable())
.map(buffer -> buffer.toString())
.flatMap(postData -> request2(client,postData) )
.forEach( httpResponse -> {
// do something with returned data);
});
}
private Flowable