Search code examples
javaspring-bootspring-webfluxreactive-programming

Webflux : Accumulate & details


I'm new to webflux and I'm trying to transform this code :

@Getter
public class Stock {
    private int value;
    private String productNumber;
    public Stock(int value, String productNumber){
        this.value = value;
        this.productNumber = productNumber;
    }
}


@Getter
public class StockResponse {
    private int value;
    private String productNumber;
    public StockResponse(int value, String productNumber){
        this.value = value;
        this.productNumber = productNumber;
    }
    public StockResponse(Stock stock){
        this.value = stock.getValue();
        this.productNumber = stock.getProductNumber();
    }

    public void add(int value){
        this.value += value;
    }
    
}

public List<StockResponse> findStockResponsesDetailsAndTotal() {
    List<StockResponse> stocksResponses = new ArrayList();
    List<Stock> stocks = stockRepository.findAll();
    StockResponse total = new StockResponse(0, "Total");
    stocks.forEach(stock -> {
        total.add(stock.getValue());
        stocksResponses.add(new StockResponse(stock));
    });
    stocksResponses.add(total);
    return stocksResponses;
}

into a "flux phylosophy" Here is my code so far :

stockRepository.findAll()
  .map(StockResponse::convert)

I'm kinda lost about the "total", I know that I can do a reduce on the Flux but i'll lose all the details in doing so


Solution

  • I find it a bit odd to add the total result as the last element in the list instead of having a dedicated class containing the total on one side and the elements on the other).

    But here's a code snippet anyway:

    Mono<List<StockResponse>> responses = findAll()
        .map(StockResponse::new).collectList().map(allStock -> {
            StockResponse total = new StockResponse(0, "Total");
            allStock.forEach(stock -> total.add(stock.value));
            List<StockResponse> result = new ArrayList<>(allStock);
            result.add(total);
            return result;
    });