RxJava - zip list of Observable

前端 未结 3 624
Happy的楠姐
Happy的楠姐 2021-02-13 02:28

I have a list of Observables (RxJava 1).

List observableList = new ArrayList<>();

It can contain at least 1 Observable.

3条回答
  •  情话喂你
    2021-02-13 02:49

    I struggled with this as well, and used Sharan's solution as a base for mine.

    My use case was doing API calls to several 3rd party providers, and then putting each individual result in a List. Each item in the list contains what the API returned, be it success or failure.

    In the end it actually looks quite elegant. In my specific case "ResultType" was replaced with something like "ApiGenericResponseObject".

    Observable.zip(listOfObservables, args -> {
        List result = new ArrayList<>();
        for (Object o: args) {
            ResultType c = (ResultType) o;
            // additional code here, I am just concatenating them together
            // This gives me a list with the individual result of each Observable (for instance an API call)
            result.add(c);
        }
        return result;
    });
    

    Alternatively, as a Lambda it looks neater. Though I wonder whether someone reading this will understand what is going on:

    Observable.zip(listOfObservables, args -> Arrays.stream(args)
        .map(object -> (ResultType) object)
        .collect(Collectors.toList())
    );
    

    Hope it helps!

提交回复
热议问题