简体   繁体   中英

How do I return a Mono after Flux's onComplete is executed?

I am trying to save a set of categories. When all categories are saved, set the categories of product to it. Then return Product. So far I've managed to do this.

public Mono<Product> save(Product product) {
    final Set<Category> categories = product.getCategories();
    Set<Category> _categorySet = new HashSet<>();
    Mono<Product> _product;
    for (Category category : categories) {
        final Mono<Category> save = categoryService.save(category);
        save.subscribe(_categorySet::add,null,()->{
            product.setCategories(_categorySet);
            repository.save(product);
        });
    }
}

How do I return product after it has been saved without relying on block() ? I cannot seem to find a source to learn these stuffs. Can someone point me to good materials.

don't block webflux chain manually. try to use this code.

public Mono<Product> save(Product product) {

    final Set<Category> categories = product.getCategories();
    return Flux.fromIterable(categories)
            .flatMap(categoryService::save)
            .collect(Collectors.toSet())
            .flatMap(categorySet -> { // use `flatMap` if repository.save(product); returns `Mono<Product>`. or else use `map` if repository.save(product); returns `Product`
                product.setCategories(categorySet);
                return repository.save(product);
            });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM