Use this operator in case you want to release multiple values on every source one. On every message of a source Observable, transforming function is expected to return an Observable that will contain values that'll be pushed through resulting Observable.
Unlike flatMap, a new outputted Observable is acknowledged immediately and sending new Observable will cancel reading the previous one.
1
import{ Observable, switchMap }from'@hullo/core';
2
β
3
let i =0;
4
β
5
newObservable(observer =>{
6
setInterval(()=>{
7
observer.next({ i: i++, t: Date.now()});
8
},1000);
9
})
10
.pipe(switchMap(
11
({ i, t })=>observable(observer =>{
12
setInterval(()=>{
13
observer.next(`${i}${Date.now()- t}`);
14
},100);
15
})
16
))
17
.subscribe({
18
next: v =>{console.log(v)}
19
})
20
21
/* Output
22
0 107
23
0 210
24
0 314
25
0 420
26
0 524
27
0 626
28
0 726
29
0 832
30
0 934
31
1 106
32
1 211
33
1 315
34
1 420
35
1 524
36
1 629
37
1 732
38
1 837
39
1 940
40
2 106
41
2 208
42
2 313
43
2 418
44
2 520
45
2 626
46
2 726
47
2 832
48
2 933
49
3 105
50
3 205
51
3 307
52
3 408
53
3 509
54
3 609
55
3 710
56
3 816
57
3 917
58
*/
Copied!
In this example the time difference between Date.now() in source and Date.now in switchMap transformation function will never be greater than a second because that is the time source needs to push a new value which will then cause creation of next comparing times Observable.