我的目标是解开一个整数列表,并获取所有元素,以便将其放在列表中。
List<Single<List<Int>>> listOfSinglesOfListofInts = getListSingleListType(); // random method that gives us that.
List<Int> intList = new ArrayList<>();
我的目标是将所有Int内容从listOfSinglesOfListOfInts移动到listInt。这是我尝试过的:
ListOfSinglesOfListOfInt.stream().map(
singleListOfInts -> singleListOfInts.map(
listOfInts -> intList.addAll(listOfInts)
)
);
return listInt;
listInt的大小始终为0。
完成此任务的正确方法是什么?
答案 0 :(得分:1)
map
操作在Flowable
链完成之前不会运行。此Flowable
已设置,但未执行。您可能想要做的是在使形状变平之后,通过阻塞收集器运行Flowable
。试试这个:
return Flowable.fromIterable(listOfSingleOfListofInt)
.flatMap(singleOfListofInt -> singleOfListofInt.toFlowable())
.flatMap(listofInt -> Flowable.fromIterable(listofInt))
.toList()
.blockingGet();
Flowable.fromIterable(listOfSingleOfListofInt)
:
List<Single<List<Int>>>
转换为Flowable<Single<List<Int>>>
flatMap(singleOfListofInt -> singleOfListofInt.toFlowable())
:
Flowable<Single<List<Int>>>
转换为Flowable<List<Int>>
flatMap(listofInt -> Flowable.fromIterable(listofInt))
:
Flowable<List<Int>>
转换为Flowable<Int>
toList()
:
Flowable<Int>
转换为Signle<List<Int>>
blockingGet()
Signle<List<Int>>
转换为List<Int>
答案 1 :(得分:0)
我在Rx-Java中做到了。
Lets consider below example to create List<Single<List<Integer>>>
List<Integer> intList = new ArrayList<>();
Collections.addAll(intList, 10, 20, 30, 40, 50);
List<Integer> intList2 = new ArrayList<>();
Collections.addAll(intList2, 12, 22, 32, 42, 52);
List<Integer> intList3 = new ArrayList<>();
Collections.addAll(intList3, 13, 23, 33, 43, 53);
Single<List<Integer>> singleList = Single.just(intList);
Single<List<Integer>> singleList2 = Single.just(intList2);
Single<List<Integer>> singleList3 = Single.just(intList3);
List<Single<List<Integer>>> listOfSinglesOfListofInts = new ArrayList<>();
Collections.addAll(listOfSinglesOfListofInts, singleList, singleList2, singleList3);
Observable
//Iterate through List<Singles>
.fromIterable(listOfSinglesOfListofInts)
//Get each single, convert to Observable and iterate to get all the integers
.flatMap(
singleListNew -> singleListNew
.toObservable()
//Iterate through each integer inside a list and return it
.flatMapIterable(integers -> integers)
)
//Get all the integers from above and convert to one list
.toList()
//Result is List<Integer>
.subscribe(
result -> System.out.println("**** " + result.toString() + " ****"),
error -> new Throwable(error)
);
希望这会有所帮助。