Home > Back-end >  How to combine Flux and Mono
How to combine Flux and Mono

Time:01-01

Assume we have the following function

fun getAnnualData(tenant: String): Flux<DashboardResponse> {

    val year = LocalDate.now().year

    val annualExpenses = expenseFinder.sumAllByYearAndTenant(year = year, tenant = tenant)
    val warehouseExpenses = expenseFinder.sumWarehouseByYearAndTenant(year = year, tenant = tenant)
    val annualRevenues = revenueFinder.sumAllByYearAndTenant(year = year, tenant = tenant)
    
    return annualExpenses.zipWith(annualRevenues)
        .filter { it.t1._id?.year == year }
        .filter { it.t2._id?.year == year }
        .map {
            DashboardResponse(
                period = Period.ANNUAL,
                expenses = it.t1,
                revenue = it.t2
            )
        }
}

and I want to add the warehouseExpenses to the returning value. How would I do that?

Where

  • annualExpenses = Flux
  • warehouseExpenses = Mono
  • annualRevenue = Flux

CodePudding user response:

You can simply use a flatMap to combine Mono:

Flux.just(...).zipWith(Flux.just(...))
        .filter(...)
        .flatMap(tuple -> Mono.just(true).map(m -> new DashboardResponse(tuple.getT1(), tuple.getT2(), m)));
  • Related