使用Reactive WebClient递归调用Mono函数

问题描述

需要从Mono递归调用Mono以获取完整的Item。 我有一个Pojo Item,在这里我将传递根ID并尝试从另一个服务获取该项目。我正在使用写服务 蓬勃发展的webflux。所以我正在使用webclient调用服务并返回Mono

其他服务将给予该物品及其直接子代。 所以我的要求是,当我传递ROOT id时,我将获得Root项目及其直接子项,Root将把LM类型的项作为子项。

获取Root项目后,我需要收集所有LM ID,并再次为每个LM ID调用ItemService,并将它们设置回根项目。

这是我的代码。发生的事情是先返回我的RootItem,然后订阅获取LM项的调用。 我想首先获取所有LM项目并将其设置为root,然后用新的LM项目响应RootItem。


String itemId,String ItemName,List<Item> items
ItemType itemType

}

Enum ItemType {

LM,ROOT,LEAF

}


getItem(itemId) {

// Returns Mono<Item> by calling anthoer service which gives me Item . Here I am using Reactive webclient to call other service.

}

getFullItem(itemId) {

    return getItem(itemId)
        .flatMap(mainItem -> {
            Predicate<Item> LM_Prdicate = p -> p.getItemType().equals(LM);
            // get the LM's from main item. at this point the LM items will not have child
            //we need to get the LM item indvidually to get its child and set back to main item.
            List<Item> LMSwihtouchild = mainItem.getItems().stream().filter(LM_Prdicate).collect(Collectors.toList()); 

            LMSwihtouchild.forEach(lmWihtoutChild -> {
                getItem(lmWihtoutChild.getId()) // here I am calling recursively to get the LM Item so that it will come with children
                .flatMap(lmWithChildren -> {
                    mainItem.getItems().removeIf(item -> item.getId().equals(lmWihtoutChild.getId())); // removing the LM item with out child from main item
                    mainItem.getContentItems().add(lmWithChildren); //Adding LM item with Children
                    return Mono.just(mainItem);
                })
                .subscribe()             
            });
            return Mono.just(mainItem); // This retruning to as  response before calling and getting the LM items with children.
        });
}

解决方法

您需要制作方法链。您不应该在.subscribe()内部执行.flatMap,因为它没有连接到您的主方法链。

我已经按照您的示例制作了伪代码。

getFullItem(itemId) {
    return getItem(itemId)
        .flatMap(mainItem -> {
            Predicate<Item> LM_Prdicate = p -> p.getItemType().equals(LM);
            List<Item> LMSwihtouchild = mainItem.getItems().stream().filter(LM_Prdicate).collect(Collectors.toList()); 

            // make flux from List<Item>. It's connected to your method chain.
            return Flux.fromIterable(LMSwihtouchild)
                .flatMap(child -> getItem(child.getId())
                .collectList()
                .map(childList -> {
                    // merge result here
                    mainItem.getItems().removeIf(item -> item.getId().equals(lmWihtoutChild.getId()));
                    mainItem.getContentItems().add(lmWithChildren);
                    return mainItem;
                }      
            });
        });
}