Change Flowable<List<Obj1>> to Flowable<List<Obj2>> in room

638 views Asked by At

How can I read a flowable list of values from room and convert it to another object which is a combination of more values from room

database.leadsDao().getLeads(leadState.name)
    .flatMap {
        val len = it.size.toLong()
        Flowable.fromIterable(it)
            .flatMap {
                Flowable.zip(
                        database.orderDao().getById(it.orderId),
                        database.orderMedicineDao().getByOrderId(it.orderId),
                        database.patientDao().getById(it.patientId),
                        Function3<Order, List<OrderMedicine>, Patient, LeadDetail>
                        { order, orderMedicines, patient -> LeadDetail.from(it, patient, order, orderMedicines) })
            }
            .take(len)
            .toList()
            .toFlowable()
    }

The code above works but I don't like the take(len) part. And without it, the stream never calls onNext of the subscriber. The stream keeps waiting for more items, which shouldn't happen since Flowable.fromIterable gives finite number or items and then ends. I.e., the code below doesn't work

database.leadsDao().getLeads(leadState.name)
    .flatMap {
        Flowable.fromIterable(it)
            .flatMap {
                Flowable.zip(
                        database.orderDao().getById(it.orderId),
                        database.orderMedicineDao().getByOrderId(it.orderId),
                        database.patientDao().getById(it.patientId),
                        Function3<Order, List<OrderMedicine>, Patient, LeadDetail>
                        { order, orderMedicines, patient -> LeadDetail.from(it, patient, order, orderMedicines) })
            }
            .toList()
            .toFlowable()
    }
1

There are 1 answers

2
Kiskae On BEST ANSWER

Flowable.fromIterable gives finite number or items and then ends.

But the Flowable.zip inside of the flatmap will not end, since Room's DAO objects emit the current value AND all future updates, so the database.*() calls that are zipped together are not finite. If you add a .first() call to the inner Flowable.zip the second version should work as well.