Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple http requests and database query with Rxjava on Android

I need to perform multiple http requests and a database query in order to filter data.

I am usin the zip operator from Rxjava

I did the following to prepare my multiple http requests

 List<Observable<List<Picture>>> requests = new ArrayList<>();


 for(String id : photoIds) {
    requests.add(pictureRepository.searchPicture(id).toObservable());
 }

I did the following to prepare my database request

Observable<List<Favourite>> favourites = pictureRepository.getFavourites().toObservable();

I try to create the observable but rxjava is not accepting my code

Observable.zip(
        requests, favourites,
        new BiFunction<Object[], List<Favourite>, List<FavouritePictures>>() {
            @Override
            public List<FavouritePictures> apply(Object[] t1, List<Favourite> t2) throws Exception {
                return /*here I want to check the favourites and return a list*/;
            }
        }
);

Is there a way to achieve this? Thanks

like image 742
Shura Capricorn Avatar asked Feb 20 '26 20:02

Shura Capricorn


1 Answers

A solution that may work for this is the following:

val photoIds = listOf(1, 2, 3)
var index = 0

Observable.just(0).flatMapSingle {
        pictureRepository.searchPicture(photoIds[index])
        index += 1
    }.repeatUntil {
        index + 1 == photoIds.size - 1
    }.toList().zipWith(pictureRepository.getFavourites(),
         BiFunction { listOfPictures, listOfFavoratePictures ->
             // Return your list
         })
  1. This observable stream will start by emitting 0;
  2. Then it will flatMap the stream to a Single Observable and return the observable stream from the searchPicture call;
  3. This process will be continued until the last item index has been reached;
  4. Then we map the result to be emitted as one list;
  5. Finally we zip the Single Observable with the getFavourites call;

You could also achieve this using a recursive method but I personally find this more readable.

like image 132
Philip Wong Avatar answered Feb 22 '26 14:02

Philip Wong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!