RxJava: how to compose multiple Observables with dependencies and collect all results at the end?

后端 未结 3 1467
终归单人心
终归单人心 2021-02-07 03:08

I\'m learning RxJava and, as my first experiment, trying to rewrite the code in the first run() method in this code (cited on Netflix\'s blog as a problem RxJava ca

3条回答
  •  孤街浪徒
    2021-02-07 03:29

    Edit: someone converted the following text, which I had added as an edit on the question, into an answer, which I appreciate, and understand may be the proper SO thing to do, however I do not consider this an answer because it's clearly not the right way to do it. I would not ever use this code nor would I advise anyone to copy it. Other/better solutions and comments welcome!


    I was able to solve this with the following. I didn't realize you could flatMap an observable more than once, I assumed results could only be consumed once. So I just flatMap f2Observable twice (sorry, I renamed some stuff in the code since my original post), then zip on all the Observables, then subscribe to that. That Map in the zip to aggregate the values is undesirable because of the type juggling. Other/better solutions and comments welcome! The full code is viewable in a gist. Thank you.

    Future f2 = executor.submit(new CallToRemoteServiceB());
    Observable f2Observable = Observable.from(f2);
    Observable f4Observable = f2Observable
        .flatMap(new Func1>() {
            @Override
            public Observable call(Integer integer) {
                System.out.println("Observed from f2: " + integer);
                Future f4 = executor.submit(new CallToRemoteServiceD(integer));
                return Observable.from(f4);
            }       
        });     
    
    Observable f5Observable = f2Observable
        .flatMap(new Func1>() {
            @Override
            public Observable call(Integer integer) {
                System.out.println("Observed from f2: " + integer);
                Future f5 = executor.submit(new CallToRemoteServiceE(integer));
                return Observable.from(f5);
            }       
        });     
    
    Observable.zip(f3Observable, f4Observable, f5Observable, new Func3>() {
        @Override
        public Map call(String s, Integer integer, Integer integer2) {
            Map map = new HashMap();
            map.put("f3", s);
            map.put("f4", String.valueOf(integer));
            map.put("f5", String.valueOf(integer2));
            return map;
        }       
    }).subscribe(new Action1>() {
        @Override
        public void call(Map map) {
            System.out.println(map.get("f3") + " => " + (Integer.valueOf(map.get("f4")) * Integer.valueOf(map.get("f5"))));
        }       
    });     
    

    And this yields me the desired output:

    responseB_responseA => 714000
    

提交回复
热议问题