如何转换 Observable<Observable<List<T>>到 Observable<List<T>> [英] How to Transform Observable&lt;Observable&lt;List&lt;T&gt;&gt;&gt; to Observable&lt;List&lt;T&gt;&gt;

查看:43
本文介绍了如何转换 Observable<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<时返回 Observable>Observable>

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);

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

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> 你会得到唯一的第一个 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>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆