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

后端 未结 2 1508
盖世英雄少女心
盖世英雄少女心 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:57

    I'm the original author of the referenced blog post about callbacks and Java Futures. Here is an example of using flatMap, zip and merge to do service composition asynchronously.

    It fetches a User object, then concurrently fetches Social and PersonalizedCatalog data, then for each Video from the PersonalizedCatalog concurrently fetches a Bookmark, Rating and Metadata, zips those together, and merges all of the responses into a progressive stream output as Server-Sent Events.

    return getUser(userId).flatMap(user -> {
        Observable> catalog = getPersonalizedCatalog(user)
                .flatMap(catalogList -> catalogList.videos().> flatMap(
                        video -> {
                            Observable bookmark = getBookmark(video);
                            Observable rating = getRatings(video);
                            Observable metadata = getVideoMetadata(video);
                            return Observable.zip(bookmark, rating, metadata, (b, r, m) -> combineVideoData(video, b, r, m));
                        }));
    
        Observable> social = getSocial(user).map(s -> {
            return s.getDataAsMap();
        });
    
        return Observable.merge(catalog, social);
    }).flatMap(data -> {
        String json = SimpleJson.mapToJson(data);
        return response.writeStringAndFlush("data: " + json + "\n");
    });
    

    This example can be seen in context of a functioning application at https://github.com/Netflix/ReactiveLab/blob/952362b89a4d4115ae0eecf0e73f273ecb27ba98/reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/routes/RouteForDeviceHome.java#L33

    Since I can't possibly provide all of the information here you can also find an explanation in presentation form (with link to video) at https://speakerdeck.com/benjchristensen/reactive-streams-with-rx-at-javaone-2014?slide=32.

提交回复
热议问题