0

How to pass an object from flatMap to subscribe in a chain? And in the code snippet below how would the blog object can be accessed down the chain?

    Single<HttpResponse<JsonNode>> singleHttpClient = httClient.post();
    singleHttpClient .toObservable().flatMap(httpResponse -> {
        if(httpResponse.getStatus() == 200) {
            JsonNode responseNode = httpResponse.getBody();
            List<JSONObject> blogObjects = iterateFrom(responseNode.getObject().getJSONArray("blogs"))
        }
        return Observable.fromIterable(blogObjects).toList().toObservable();
    }).flatMap(jsonObjects -> Observable.fromIterable(jsonObjects))
            .flatMap(jsonObject -> {
                return Observable.just(new Blog(jsonObject.getString("id"), jsonObject.getString("guid")));
            }).flatMap(blog -> {
                Single<HttpResponse<JsonNode>> singleHttpClient2 = httpClient2.post();
                singleHttpClient2.getParams().put("guid", blog.getImageGuid());
                return singleHttpClient2.postAsBinary().toObservable();
            }).subscribe(javaScriptObjectHttpResponse -> {
                JavaScriptObject jsoBody = javaScriptObjectHttpResponse.getBody();
                doSomethingWith(blog, jsBody); // How to access `blog` from here?
            });
quarks
  • 33,478
  • 73
  • 290
  • 513

2 Answers2

1

Use zipWith method like below.Create variable in Blog object that hold your blog data response from server and create getter and setter for that data variable.

Single<HttpResponse<JsonNode>> singleHttpClient = httClient.post();
    singleHttpClient .toObservable().flatMap(httpResponse -> {
        if(httpResponse.getStatus() == 200) {
            JsonNode responseNode = httpResponse.getBody();
            List<JSONObject> blogObjects = iterateFrom(responseNode.getObject().getJSONArray("blogs"))
        }
        return Observable.fromIterable(blogObjects).toList().toObservable();
    }).flatMap(jsonObjects -> Observable.fromIterable(jsonObjects))
            .flatMap(jsonObject -> {
                return Observable.just(new Blog(jsonObject.getString("id"), jsonObject.getString("guid")));
            }).flatMap(blog -> {
        Single<HttpResponse<JsonNode>> singleHttpClient2 = httpClient2.post();
        singleHttpClient2.getParams().put("guid", blog.getImageGuid());
        return Observable.zipWith(singleHttpClient2.postAsBinary().toObservable(), (Blog blog, HttpResponse data)->blog.setData(data));
    }).subscribe(blog -> {
        doSomethingWith(blog); // How to access `blog` from here?
    });
KuLdip PaTel
  • 1,069
  • 7
  • 19
0

In project-reactor an operator named zip exists for binding Monos and Fluxes (similar to Observables in rx-java) so that multiple items can be passed down (as a Tuple) the pipeline.

Similar operator should exist for rx-java.

Helpful stack-overflow question, Rxjava Android how to use the Zip operator

Nipuna Saranga
  • 970
  • 13
  • 18