How to compose Observables to avoid the given nested and dependent callbacks?

后端 未结 2 1509
盖世英雄少女心
盖世英雄少女心 2020-12-04 20:23

In this blog, he gives this (copy/pasted the following code) example for the callback hell. However, there is no mention of how the issue can be eliminated by using Reactive

2条回答
  •  眼角桃花
    2020-12-04 20:40

    According to your code. Suppose that the remote call are done using Observable.

     Observable  callRemoveServiceA()  { /* async call */  }
    
    /* .... */
    
    Observable  callRemoveServiceE(Integer f2) { /* async call */  }
    

    What you want :

    • call serviceA then call serviceB with the result of serviceA
    • call serviceC then call serviceD and serviceE with the result of serviceC
    • with the result of serviceE and serviceD, build a new value
    • display the new value with the result of serviceB

    With RxJava, you'll achieve this with this code :

    Observable f3 = callRemoveServiceA() // call serviceA
                // call serviceB with the result of serviceA
                .flatMap((f1) -> callRemoveServiceB(f1)); 
    
    
    Observable f4Andf5 = callRemoveServiceC() // call serviceC
                        // call serviceD and serviceE then build a new value
                        .flatMap((f2) -> callRemoveServiceD(f2).zipWith(callRemoveServiceE(f2), (f4, f5) -> f4 * f5));
    
    // compute the string to display from f3, and the f4, f5 pair
    f3.zipWith(f4Andf5, (childF3, childF4Andf5) -> childF3 + " => " + childF4Andf5)
                // display the value
                .subscribe(System.out::println);
    

    the important part here is the use of flapMap and zip (or zipWith)

    • flapMap will transform a value into another Observable. This Observable here will be your new asynchronos call. ( http://reactivex.io/documentation/operators/flatmap.html )
    • zip will compose a new value from two different Observable. So you can build a new value with the result of two (or more) Obsevable ( http://reactivex.io/documentation/operators/zip.html )

    You can get more info on flapMap here : When do you use map vs flatMap in RxJava?

提交回复
热议问题