[英]How to process first n items and remaining one differently in a observable stream
for example, 例如,
given a stream of a certain number (m) of numbers (m1, m2, m3, m4, m5, m6...), and apply a transformation (2 * i) to first n items (n can be less, equal or larger than m), apply another transformation (3 * i) to the remaining items. 给定一定数量(m)的数字流(m1,m2,m3,m4,m5,m6 ......),并对前n项应用变换(2 * i)(n可以更小,相等或者大于m),对其余项目应用另一个转换(3 * i)。 and
和
return result : m1*2, m2*2, m3*3, m4*3, m5*3, m6*3... (assuming n=2 here). 返回结果:m1 * 2,m2 * 2,m3 * 3,m4 * 3,m5 * 3,m6 * 3 ...(假设这里n = 2)。
I was trying to use take(n) and skip(n) and then concatwith, but looks like take(n) will drop the remaining items in the sequence , and make skip(n) after that return nothing. 我试图使用take(n)和skip(n)然后concatwith,但看起来take(n)将删除序列中的剩余项目,并在之后返回任何内容后跳过(n)。
You can share your m's stream, and then merge back together take()
and skip()
streams, something like this: 您可以共享m的流,然后将
take()
和skip()
流合并回来,如下所示:
int m = 10;
int n = 8;
Observable<Integer> numbersStream = Observable.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.publish();
Observable<Integer> firstNItemsStream = numbersStream.take(n)
.map(i -> i * 2);
Observable<Integer> remainingItemsStream = numbersStream.skip(n)
.map(i -> i * 3);
Observable.merge(firstNItemsStream, remainingItemsStream)
.subscribe(integer -> System.out.println("result = " + integer));
numbersStream.connect();
EDIT: 编辑:
As point out by @AE Daphne, share()
will start emitting with the first subscriber, thus second subscriber might miss notification/s if the Observable started already to emit item/s, so in this case there are other possibilities: 正如@AE Daphne指出的那样,
share()
将开始与第一个订阅者一起发送,因此如果Observable已经开始发出item / s,则第二个订阅者可能会错过notification / s,因此在这种情况下还有其他可能性:
cache()
- will reply all cache emitted items and reply them to each new subscriber, but will sacrifice the unsubscription ability, thus need to be used carefully. cache()
- 将回复所有缓存发出的项目并将其回复给每个新订阅者,但会牺牲取消订阅能力,因此需要谨慎使用。
reply().refCount()
- will create Observable
that reply()
all previous items to each new Subscriber (similar to cache), but will unsubscribe when the last subscriber unsubscribe from it. reply().refCount()
- 将创建Observable
,它reply()
所有以前的每个新订阅者的项目(类似于缓存),但是当最后一个订阅者取消订阅时将取消订阅。
In both cases, memory should take into consideration as the Observable
will cache all emitted items in memory. 在这两种情况下,都应该考虑内存,因为
Observable
会将所有发出的项缓存在内存中。
publish()
- Additional possibility, without caching all previous items, would be to use publish()
to create ConnectableObservable
, and call it's connect()
method to begin emissions after all required subscribers subscribed, thus will get synchronization and all subscribers will get all notifications correctly. publish()
- 在没有缓存所有先前项目的情况下,使用publish()
创建ConnectableObservable
,并在所有订阅者订阅后调用它的connect()
方法开始排放,从而获得同步并且所有订阅者将获得所有通知正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.