使用Reactive Web客户端递归调用Mono函数



需要从Mono递归调用Mono才能获得表单完整的Item。我有一个Pojo项目,在这里我会传递根id,并尝试从另一个服务获取该项目。我正在使用编写服务sprign webflux。所以我使用网络客户端调用服务并返回Mono

另一项服务将提供物品及其直系亲属。所以我的要求是,当我传递ROOT id时,我将获得ROOT项及其直接子项,ROOT将有LM类型的项作为子项。

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

这是我的代码。发生的事情是,首先我的RootItem正在返回,然后获取LM项目的调用正在订阅。我想首先获取所有LM项目,并将它们设置为根,然后用新的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.
});
}

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

我通过你的例子制作了伪代码。

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;
}      
});
});
}

最新更新