Skip to content

Commit 13a2e2b

Browse files
committed
3.4 Added switchMap
1 parent d57adb7 commit 13a2e2b

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

Part 3 - Taming the sequence/4. Combining sequences.md

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ Observable.switchOnNext(
429429
.map(i2 -> i)
430430
)
431431
)
432-
.take(10)
432+
.take(9)
433433
.subscribe(System.out::println);
434434
```
435435
Outpu
@@ -443,11 +443,42 @@ Outpu
443443
2
444444
2
445445
2
446-
3
447446
```
448447

449448
This example may be a bit confusing. What we've done is create an observable that creates a new observable every 100ms. Every created observable emits it's number in the sequence every 30ms.
450449

450+
#### switchMap
451+
452+
Where `flatMap` internally uses `merge` to combine the generated sequences, there is `switchMap` to use `switchOnNext` in place of `merge`.
453+
454+
```java
455+
public final <R> Observable<R> switchMap(Func1<? super T,? extends Observable<? extends R>> func)
456+
```
457+
![](https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchMap.png)
458+
459+
Every value from the source observable is mapped through `func` to an observable. The values from the generated observable are emitted by the returned observable. Every time a new value arrives, `func` generates a new observable and switches to it, dropping the old one. The example we showed for `switchOnNext` can also be implemented with `switchMap`:
460+
461+
```java
462+
Observable.interval(100, TimeUnit.MILLISECONDS)
463+
.switchMap(i ->
464+
Observable.interval(30, TimeUnit.MILLISECONDS)
465+
.map(l -> i))
466+
.take(9)
467+
.subscribe(System.out::println);
468+
```
469+
Output
470+
```
471+
0
472+
0
473+
0
474+
1
475+
1
476+
1
477+
2
478+
2
479+
2
480+
```
481+
451482

452483
## Pairing sequences
453484

0 commit comments

Comments
 (0)