android - 合并、压缩或如何将流包含或压缩到流中
问题描述
我不确定到底要使用什么,但最近,当我使用包含所有内容的流的代码时,我在使用 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() ,以便最终我在流中仍然有一个ListItem的Single。
我正在尝试使用 combine,但无法真正使其工作,当我有需要“插入”并留下可用于处理的内容的流时,我发现 RxJava 有点奇怪。
欢迎任何澄清。
解决方案
//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");
}
希望这个解决方案能让您大致了解您想要实现的目标。如果我错过了什么,请告诉我,以便我可以更新这个答案。
推荐阅读
- google-cloud-dataflow - 将 PColll 行的一个字段写入 BQ - 需要整行用于表选择
- vue.js - Vue 和 Vuex v-for 在状态更改时无法正确更新
- flutter - 如何在使用 GetX 时更新 FutureBuilder 中的未来以获取新数据
- javascript - vuejs:如何在 v-for 中使用 v-model 并观看
- matlab - 用 silvester 矩阵求解丢番图方程
- scala - 没有 Scala 的联合泛型类型
- css - 如何修复背景图像不扩展 wp 模板页面的全高,启用封面和 100% w/h
- php - 在 Wordpress 中从 SQL 数据库中收集行
- python - 如何在 R 中对网络优化模型进行敏感性分析?
- python - 如何找到最小表单输入