RxJava — Practical takeUntil Example

Niklas Baudy
3 min readAug 5, 2016

Last week I had the following problem:

- I had to send different model objects of the same type to the backend
- There was no backend API to send all models at once
- Once the backend returned a successful response I should stop sending further model objects

Since the source of model objects was already reactive and I already had a way of sending one model to the backend in a reactive manner too I
decided to stick with the reactive approach.

I was thinking of which operator would make the most sense here and I remembered takeUntil.

From the documentation:

Returns an Observable that emits items emitted by the source Observable, checks the specified predicate
for each item, and then completes if the condition is satisfied.

Sounds pretty good right, so how do we actually wire it up?

First let’s get our models that we need to send.

modelProvider.getItems()

This is our source Observable. The next thing to do is for each object a backend request. FlatMap comes in handy there.

modelProvider.getItems()
.flatMap(retroApiInterface::doBackendRequest)

I’m using Retrofit here to send a backend request which will return an Observable that emits the matching response.

--

--