Skip to content

Commit b7700ea

Browse files
committed
Added explanation of collect
1 parent 0467a5d commit b7700ea

1 file changed

Lines changed: 28 additions & 1 deletion

File tree

Part 2 - Sequence Basics/4. Aggregation.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,34 @@ Output
242242
[10, 11, 12, 13, 14]
243243
```
244244

245-
You don't have to do this manually. Rxjava offers a variety of operators for collecting your sequence into a container. Those aggregators return an observable that will emit the corresponding collection when it is ready.
245+
The code above has a problem with a formality: `reduce` is meant to be a functional fold and folds are not supposed to work on mutable accumulators. If we were to do this the "right" way, we would have to create a new instance of `ArrayList<Integer>` for every new item, like this:
246+
247+
```java
248+
// Formally correct but very inefficient
249+
.reduce(
250+
new ArrayList<Integer>(),
251+
(acc, value) -> {
252+
ArrayList<Integer> newAcc = (ArrayList<Integer>) acc.clone();
253+
newAcc.add(value);
254+
return newAcc;
255+
})
256+
```
257+
258+
#### collect
259+
260+
The performance of creating a new collection for every new item is unacceptable. For that reason, Rx offers the `collect` operator, which does the same thing as `reduce`, only using a mutable accumulator this time. By using `collect` you document that you are not following the convention of immutability and you also simplify your code a little:
261+
262+
```java
263+
Observable<Integer> values = Observable.range(10,5);
264+
265+
values
266+
.collect(
267+
() -> new ArrayList<Integer>(),
268+
(acc, value) -> acc.add(value))
269+
.subscribe(v -> System.out.println(v));
270+
```
271+
272+
Usually, you won't have to collect values manually. Rxjava offers a variety of operators for collecting your sequence into a container. Those aggregators return an observable that will emit the corresponding collection when it is ready.
246273

247274
#### toList
248275

0 commit comments

Comments
 (0)