首页 > 解决方案 > 合并、压缩或如何将流包含或压缩到流中

问题描述

我不确定到底要使用什么,但最近,当我使用包含所有内容的流的代码时,我在使用 RxJava 时遇到了很多麻烦。

在我的情况下,假设我必须获取一个对象的实例,我需要从可用的流中进行一些处理,让我们称之为 NeededInstance,这样我就可以访问 NeededInstance 的 Observable。

接下来,我正在做的是我有一个SomeObject列表要做的是我需要遍历所有项目并更新它们。

我通过以下方式执行此操作:

.map(/*in this map the Single<List<SomeObject>> is created*/)
.flatMap(Single<List<SomeObject>> -> updateWithData(Single<List<SomeObject>>); 

这就是我希望我的 updateWithData 函数的样子:

private Single<List<SomeObject>> updateWithData(List<SomeObject> list) {
return 
Observable.just(list)
.flatMapIterable(listItem -> listItem)
.flatMapSingle(listItem -> updateListItem(listItem))
.toList();
}

我执行上面的代码,以便我可以将链从处理单个列表转换为我更新并再次返回到列表的可观察项目。下面是 updateListItem 函数,当我尝试从我在开头提到的其他流中获取某些内容时,麻烦就来了:

updateListItem(ListItem listItem) {
return
Observable<NeededInstance>.map(Optional::get)
.flatMapSingle(neededInstance -> workWithListItemAndNeededInstace(listItem, neededInstance))
.map(integer -> {
// do something with integer soming from the above method and with a listItem passed into this function
}
return Single.just(updatedListItem)
}

所以,可以肯定的是,workWithListItemAndNeededInstance 不能更新 listItem,我只是在那里得到一个 Integer 对象,我必须自己更新 listItem。然后我试图返回一个 listItem 的 Single 或 listItem 本身,并以某种方式使其可用于 .toList() ,以便最终我在流中仍然一个ListItemSingle

我正在尝试使用 combine,但无法真正使其工作,当我有需要“插入”并留下可用于处理的内容的流时,我发现 RxJava 有点奇怪。

欢迎任何澄清。

标签: androidrx-java2

解决方案


//You have a list of string object
List<String> intList = new ArrayList<>();
Collections.addAll(intList, "1", "2", "3", "4", "5");

//Now what you want here is append neededInstance to each item in list and get it as a list.
//So output would be like List of (test1, test2, test3, test4, test5);

Observable
    //iterate through the list of items and pass one by one to below stream
    .fromIterable(intList)
    //Each item from the list is passed down to workWithListItemAndNeededInstace
    .flatMap(item -> workWithListItemAndNeededInstace(item))
    .toList()
    .subscribe();

/*
This method will combine item from list with the neededInstance and return a stream of combined data
*/
private Observable<String> workWithListItemAndNeededInstace(String item) {
    return neededInstance().map(instance -> instance + item);
}

/*
This will be your stream from which you get needed stream
 */
private Observable<String> neededInstance() {
    return Observable.just("Need instance");
}

希望这个解决方案能让您大致了解您想要实现的目标。如果我错过了什么,请告诉我,以便我可以更新这个答案。


推荐阅读