ejay
ejay

Reputation: 1144

RxJava - Combine 2 calls

I have 2 Observables, which call 2 WS

  1. Get a list of cars (at this point, each car from this list doesn't have his owner)
  2. Get the owner of the car

So first I get the list of cars. Everything is ok. But I would to get the owner for each car and set it in the Car entity, like car.setOwner(owner) and send the final list of cars, containing their owner.

Api.getCars()
.subscribe(new Action1<List<Car>>() {
    @Override
    public void call(List<Car> cars) {
    // get the list of cars, but need to get their owner
    });

Which is the best way to do this? (Moreover, without lambdas.)

Upvotes: 0

Views: 379

Answers (1)

Maksim Ostrovidov
Maksim Ostrovidov

Reputation: 11058

You could utilize this flatMap overload:

Api.getCars()
    .flatMap(cars -> Observable.from(cars)) // flatten your list
    .flatmap(car -> Api.getOwner(car), // request each owner
            (car, owner) -> {
                car.setOwner(owner); // assign owner to the car
                return Observable.just(car);
            })
    .toList() // collect items into List
    ... // here is your Observable<List<Car>>

Upvotes: 2

Related Questions