Search code examples
androidrx-javazip-operator

How to make a set of parallel of undefined number of requests using rxJava in Android?


Currently I have a service that returns that returns a list of parameters. if there are 4 parameters I need to perform one request per parameter to the same endpoint using the each of the parameter. After that I need to save the list of results of all the request into a collection. If I don't know how many request do I have to perform, What rxJava operator I need to use and how should I use it?? . Take into account that I don't need to wait for the answer of the first request to perform the second one and ....

I have seen that the zip operator allow me to perform parallel request but I have to know the number of request to use it.


Solution

  • At the end I implemented it this way:

    public Subscription getElementsByStage(List <String> requiredStages) {
        List < Observable <ElementsResponse>> observables = new ArrayList < > ();
        for (String stage: requiredStages) {
            ElementsRequest request = buildElementRequest(stage);
            observables.add(request).subscribeOn(Schedulers.newThread()));
        }
        Observable zippedObservables = Observable.zip(observables, this::arrangeElementsByStage);
        return zippedObservables
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber <HashMap<Stage,Element>>() {
               .....
            }
      }