如何从 List<Single<List<Int>> 中收集所有整数并将其放入 RxJava

我的目标是解开一个整数列表的单项列表,并获取它的所有元素,以便将它放在一个列表中。


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。


实现这一目标的正确方法是什么?


繁星淼淼
浏览 178回答 2
2回答

ABOUTYOU

map在Flowable链完成之前,操作不会运行。这Flowable是设置,但没有执行。您可能想要做的是Flowable在展平形状后通过阻塞收集器。试试这个:return Flowable.fromIterable(listOfSingleOfListofInt)&nbsp; &nbsp; .flatMap(singleOfListofInt -> singleOfListofInt.toFlowable())&nbsp; &nbsp; .flatMap(listofInt -> Flowable.fromIterable(listofInt))&nbsp; &nbsp; .toList()&nbsp; &nbsp; .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>

慕的地10843

我在 Rx-Java 中做到了。Lets consider below example to create List<Single<List<Integer>>>&nbsp;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&nbsp; &nbsp; //Iterate through List<Singles>&nbsp; &nbsp; .fromIterable(listOfSinglesOfListofInts)&nbsp; &nbsp; //Get each single, convert to Observable and iterate to get all the integers&nbsp; &nbsp; .flatMap(&nbsp; &nbsp; &nbsp; &nbsp; singleListNew -> singleListNew&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toObservable()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Iterate through each integer inside a list and return it&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMapIterable(integers -> integers)&nbsp; &nbsp; )&nbsp; &nbsp; //Get all the integers from above and convert to one list&nbsp; &nbsp; .toList()&nbsp; &nbsp; //Result is List<Integer>&nbsp; &nbsp; .subscribe(&nbsp; &nbsp; &nbsp; &nbsp; result -> System.out.println("**** " + result.toString() + " ****"),&nbsp; &nbsp; &nbsp; &nbsp; error -> new Throwable(error)&nbsp; &nbsp; );希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java