I’m trying to better understand concepts or RxJS, and here is a simple example that I wasn’t sure if I understood everything correctly:
from([1,2,3,]).pipe(
map((data)=>{
console.log(data,'map');
return data
})
)
.subscribe(data=>console.log(data, 'from subscribe'))
/*
1 map
1 from subscribe
2 map
2 from subscribe
3 map
3 from subscribe
*/
Here is what I think happens:
- When we call
subscribe, firstmapsubscribes tofromObservable. - Each value emitted by
fromis console logged and emitted back frommapas an individual Observable. So, in this case we would have 3 Observables. .subscribesubscribes to each Observable frommap(Observable that resolves with 1, another Observable that resolves with 2, …. ) and we see another log.
After looking at documentation, I think I got something wrong with my current understanding of how things are working.
I’d appreciate if someone could confirm or correct the logic I described in my question.
>Solution :
from-> converts the array into a stream of observables that are emitted one by one.map-> accesses the value of the observable and you have the option to transform the data if needed, the input parameter is not a observable, the output value is also not an observable.subscribe-> for each emitted value the subscribe next block is called (the function which is passed.
Subscribe has three sections, subscribe has three arguments.
next-> called when an observable emits an value, will continue to be called on each emit until the observable completeserror-> called when an there is an error on the observable stream, could be non intentional (coding error) or manual errorthrow new Error('failed')complete-> will get called once the observable stream completes.
In your example, next block is called three times (in your case the console.log) after that finally the complete block is called. To better understand it, here is a working example highlighting the same!
import './style.css';
import { rx, of, map, from } from 'rxjs';
from([1, 2, 3])
.pipe(
map((data) => {
console.log(data, 'map');
return data;
})
)
.subscribe({
next: (data: any) => {
console.log(data, 'from subscribe next');
},
error: (data: any) => {
console.log(data, 'from subscribe error');
},
complete: () => {
console.log('from subscribe complete');
},
});