This is exactly the same problem as this:
RX: How to wait for subscribers to finish?
I have a producer which can produce object faster than subscriber so I want it to produce objects in parallel but block after some fixed number of items.
Like this:
- publisher produces items
- as soon as 10 items are produced, subscriber takes them and start processing
- publisher continues to produce and buffer items in parallel, but if next 10 are produced, then it waits for subscriber
- after finishing processing, subscriber immediately takes next 10 objects from the buffer
- publisher continues to produce and buffer items
- etc.
Current solution:
val bars = Flowable.fromStream(foos)
// calculate is faster
.map(foo -> calculateBars(foo))
.buffer(10)
// than saving to database
.flatMap(bars -> Flowable.fromStream(saveBars(bars)))
.collect(Collectors.toSet())
.blockingGet();
If I add .observeOn(Schedulers.io()) then publisher doesn't wait at all for consumer and eventually crash with OutOfMemoryError. If I remove it it waits all the time instead of preparing the next batch of items.
This is related to my other question https://stackoverflow.com/questions/73660953/keep-memory-usage-constant-with-jparepository-andrxjava . I think that solving this issue will solve that.