Android rxjava cache network call

OK, so I'm working on a project. I need to get the JSON from the server, get the corresponding POJO, fill in some views and finish

The problem I face is that I have to nest network calls to get the required final data. In order to minimize network calls, I have to reuse them, which leads to a really complex rxoperator chain. 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; }

Explain operator chain (this is an example)

>Get all car IDS (network phone 1) > for each car number, find the real car > get the car model from the car ID (network call 2) > update the view with the car model > get all car IDS (network phone 3) > for each car number, find the truck > get the truck model from the car ID (network phone 4) > update the view with the truck model

Therefore, network call 1 is the same as network call 3, so I should reuse them, which means I should only call once and save the data. That's why RX operator is linked above

My question is, is there any way to do this, but cache network Call1 instead of this terrible and incomprehensible operator chain?

I don't know how caching works. How can I apply this operator to this situation?

resolvent:

Cache is exactly what you need. This is your usage:

cachedCarIds = getCarIds().cache();

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

Cache () will ensure that the subscription ID is executed only once (at the first subscription) and that all its values are saved for future subscribers

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>