Search code examples
androidrx-javachain

RxJava cache network calls


Ok so i'm working on a project and i need to get Json from a server, get the corresponding POJOs, fill some views and end.

The problem i am facing is that, i have to nest network calls to get the final data i need. And in order to minimize the network calls, i have to reuse them, and that leads to really complex RxOperator chains. For example:

getCarId() // network call
   .flatMap(carIdObj -> getCarModelById(carIdObj)
                           .doOnNext(... update car views)
                           .flatMap(carModelObj -> { return carIdObj;}     
   .flatMap(carIdObj --> getTruckModelById(carIdObj)
                           .doOnNext(... update truck views)
                           .flatMamp(truckModelObj -> { return carIdObj; }

Explaining the operator chains (this is an example)

  • get all car Ids (network call1)
  • for each car id, find the real cars
  • get car model from car id (network call2)
  • update view with car model
  • get all car Ids (network call3)
  • for each car id, find the trucks
  • get truck model from car id (network call4)
  • update view with truck model

So, network call1 and network call 3 are the same, so i should reuse them, which means, i should just call it once and save the data. That why the Rx-Operator chains above.

My question is, is there any way of accomplish the same, but by caching the network call1 instead of this horrible unreadable operator chain?

I don't understand how cache work, how can i apply this operator to this scenario?


Solution

  • cache is exactly what you need and here's how you use it:

    cachedCarIds = getCarIds().cache();
    
    cachedCarIds.map(this::getCarModelById).subscribe(... update car views);
    cachedCarIds.map(this::getTruckModelById).subscribe(... update truck views);
    

    cache() will ensure the subscription id done only once (upon first subscription), and all its values are saved for future subscribers.