Skip to content

Commit 2d67a60

Browse files
committed
Add FlatMap Transformation Example
1 parent 75abc58 commit 2d67a60

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
3+
*
4+
* The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable,
5+
* where that function returns an Observable that itself emits items. FlatMap then merges the emissions of these resulting Observables,
6+
* emitting these merged results as its own sequence.
7+
This method is useful, for example, when you have an Observable that emits a series of items that themselves have Observable members or
8+
are in other ways transformable into Observables, so that you can create a new Observable that emits the complete collection of items
9+
emitted by the sub-Observables of these items.
10+
Note that FlatMap merges the emissions of these Observables, so that they may interleave.
11+
* */
12+
13+
package TransformingObservables;
14+
15+
import rx.Observable;
16+
17+
public class FlatMap {
18+
public static void main(String[] args) {
19+
Observable.just(1, 2, 3)
20+
.flatMap(integer -> Observable.just("A", "B", "C").map(integer1 -> integer + integer1))
21+
.subscribe(
22+
integer -> System.out.println(integer),
23+
throwable -> System.out.println("Error"),
24+
() -> System.out.println("Complete")
25+
);
26+
27+
28+
System.out.println("---------------------");
29+
Observable.just(1, 2, 3)
30+
.flatMap(integer -> addOne(integer))
31+
.flatMap(integer -> multiplyByTwo(integer))
32+
.subscribe(integer -> System.out.println(integer),
33+
throwable -> System.out.println("Error"),
34+
() -> System.out.println("Completed")
35+
);
36+
}
37+
38+
39+
//needs to return Observable
40+
public static Observable<Integer> addOne(int x) {
41+
return Observable.just(x + 1);
42+
}
43+
44+
45+
public static Observable<Integer> multiplyByTwo(int x) {
46+
return Observable.just(x * 2);
47+
}
48+
}
49+
50+
51+
/*
52+
* OUTPUT:
53+
1A
54+
1B
55+
1C
56+
2A
57+
2B
58+
2C
59+
3A
60+
3B
61+
3C
62+
Complete
63+
---------------------
64+
4
65+
6
66+
8
67+
Completed
68+
* */
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package TransformingObservables;
2+
3+
import rx.Observable;
4+
import rx.functions.Func1;
5+
6+
public class GroupBy {
7+
public static void main(String[] args) {
8+
// Observable.just(1,2,3).groupBy(integer -> integer%2)
9+
// .flatMap(booleanIntegerGroupedObservable ->booleanIntegerGroupedObservable.subscribeOn(s->System.out.println(s)) );
10+
11+
}
12+
}

0 commit comments

Comments
 (0)