Search code examples
javarx-java2

How can I merge both values using Single.flatMap?


I have this code:

private Single<Invoice> getInvoiceWithItems() {
    return getInvoice().flatMap(invoice -> getItems(invoice)); // <--- Here, I need invoice and items
}

private Single<Invoice> getInvoice() { ... }

private Single<List<Item>> getItems(Invoice invoice) { ... }

I want to do something like invoice.setItems(items). I tried passing an extra function parameter to flatMap but it doesn't accept it.

How can I do it?

I found this solution, but I'm not sure if it is the best one:

private Single<Invoice> getInvoiceWithItems() {
    return Single.zip(getInvoice(), getInvoice().flatMap(invoice -> getInvoiceItems(invoice)), (invoice, items) -> {
        invoice.setItems(items);
        return invoice;
    });
}

Solution

  • private Single<Invoice> getInvoiceWithItems() {
        return getInvoice().flatMap(invoice -> getItems(invoice).map(items -> {
            invoice.setItems(items);
            return invoice;
        }));
    }