Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect all ints from List<Single<List<Int>>> and put it into List<Int> in RxJava?

Tags:

java

rx-java

My goal is to unwrap a list of singles of list of ints, and get all it's elements, in order to put it on a list.

List<Single<List<Int>>> listOfSinglesOfListofInts = getListSingleListType(); // random method that gives us that.
List<Int> intList = new ArrayList<>();

My goal is to move move all Int contents from listOfSinglesOfListOfInts to listInt. Here is what I tried:

ListOfSinglesOfListOfInt.stream().map(
    singleListOfInts -> singleListOfInts.map(
        listOfInts -> intList.addAll(listOfInts)
    )
);


return listInt;

The size of listInt is always 0.

What would be the correct way of accomplishing this?

like image 201
Don Code Avatar asked Oct 16 '25 22:10

Don Code


1 Answers

map operations do not run until the Flowable chain is completed. This Flowable is set up, but is not executed. What you probably want to do is run the Flowable through a blocking collector after flattening the shape. Try this:

return Flowable.fromIterable(listOfSingleOfListofInt)
    .flatMap(singleOfListofInt -> singleOfListofInt.toFlowable())
    .flatMap(listofInt -> Flowable.fromIterable(listofInt))
    .toList()
    .blockingGet();

Details

Flowable.fromIterable(listOfSingleOfListofInt):

  • Transform List<Single<List<Int>>> into Flowable<Single<List<Int>>>

flatMap(singleOfListofInt -> singleOfListofInt.toFlowable()):

  • Transform Flowable<Single<List<Int>>> into Flowable<List<Int>>

flatMap(listofInt -> Flowable.fromIterable(listofInt)):

  • Transform Flowable<List<Int>> into Flowable<Int>

toList():

  • Transform Flowable<Int> into Signle<List<Int>>

blockingGet()

  • Transform Signle<List<Int>> into List<Int>
like image 149
flakes Avatar answered Oct 19 '25 12:10

flakes