如何转换 Observable<Observable<List<T>>到 Observable<List<T>>

编程入门 行业动态 更新时间:2024-10-28 16:18:30
本文介绍了如何转换 Observable&lt;Observable<List<T>>到 Observable<List<T>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我被困在如何将以下可观察类型转换/转换为我的目标类型:

I am stuck on how to convert/transform the following observable type to my target type:

我有 observable 类型:

I have observable of type:

Observable<Observable<List<FooBar>>>

我想将其转换为:

Observable<List<FooBar>>

所以当我订阅它时,它发出 List 而不是 Observable

So when I subscribe on it, it emits List<FooBar> not Observable<List<FooBar>>

我尝试使用 map、flatMap...我找不到解决方案.

I tried with map, flatMap... I could not find a solution.

但是,我发现了一个看起来很奇怪的运算符,名为 blockingFirst,我的 IDE 表明它在应用于 Observable<时返回 ObservableObservable

However, I found a strange looking operator called blockingFirst which my IDE indicates that it returns Observable<List<FooBar>> when applied to Observable<Observable<List<FooBar>>>

但是阻塞"部分让我很困惑.

But the 'blocking' part is confusing me.

我也在寻找比 blockingFirst 更好的解决方案,如果有的话.

I am also looking for better solution than blockingFirst one, if any.

推荐答案

flatMap 确实是要走的路:

Observable<Observable<List<FooBar>>> streamOfStreams = ... Observable<List<FooBar>> listStream = streamOfStreams.flatMap(listObservable -> listObservable);

我觉得你应该换个角度看,从一种类型转换到另一种类型并不简单.Observables 的 Observable 表示发出流的流,每个流都发出一些项目的列表.您想要实现的是将其展平为单个流,该流从所有流中发出所有列表.flatMap 完全正确,你给它一个项目发射,并返回一个 Observable,flatMap 将订阅返回的 Observable 并将从它发出的每个项目合并到源流中,在这种情况下,因为您只需返回每个项目的发射,即 Observable

I think you should look at it in a different perspective, it is not simple converting from 1 type to another type. Observable of Observables means stream that emit streams that each of them emit a list of some items. what you want to achieve is to flatten it to single stream that emit all the lists from all the streams. flatMap doing it exactly, you give it an item emission, and return an Observable, flatMap will subscribe to the returned Observable and will merge each item emitted from it to the source stream, in this case, as you simply return each item emission which is Observable<List<FooBar>>, you practically taking each emitted Observable , subscribe to it, and merge all its list emissions back, so you get back stream of all the lists from all the Observables.

blockingFirst 绝对不是要走的路,它所做的是等待(阻止)直到第一次发射并仅返回此项目,因为您的项目 ar Observable

blockingFirst is definitely not the way to go, what it does is to wait (block) until first emission and return this item only, as your items ar Observable<List<FooBar>> you'll get the only first Observable. so while it indeed has the same type, its clearly not the same stream you want.

更多推荐

如何转换 Observable<Observable<List<T>>到 Observable<List<T>&

本文发布于:2023-11-08 16:36:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569901.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:lt   Observable   gt   List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!