Suppose
Observable<Integer> obs = Observable.just(1, 2, 3, 4, 5);
I need a sequence, where each even number of obs
multiplied by count of even numbers in obs
, and each odd number of obs
multiplied by count of odd numbers in obs
.
I.e. in given case there are 2 evens and 3 odds, so result sequence must be
3 (1 * 3)
4 (2 * 2)
9 (3 * 3)
8 (4 * 2)
15 (5 * 3)
How can I do it?
You can achieve it with splitting the
Observable
to odd and even streams, then iterate over each stream and multiply by the count of each split stream:if you're doing it over in-memory lists/arrays you might consider using
Java 8 Stream API
, and doing the same, the code is very similar:in my machine it runs faster with order of magnitude (~ x12 ).
If the source of items/numbers id over time producer consider optimizing the Reactive approach to avoid resubscribe multiple times to
Observables
(replay/cache etc.)This worked for me.
Traverse twice.