RxJS `flatMap` behavior is different from intuition

Asked 1 years ago, Updated 1 years ago, 22 views

Regarding the output of the code below,

var source=Rx.Observable
.range(1,3)
.flatMap(function(v){
    return Rx.Observable.range(1,3);
})
.subscribe(function(v){
    console.log(v)
});

Below is the list.

1
2
1
3
2
1
3
2
3

However, the result I imagined was

1
2
3
1
2
3
1
2
3

I don't understand it at all when I look at the official document.

Could someone explain why this is happening? Thank you!

javascript rx-javascript

2022-09-30 16:43

1 Answers

This is not due to flatMap, but to the Observable.range scheduler.

If you look inside the Observable.range, you will find that by default you are using a scheduler called Scheduler.currentThread.
In order to achieve the expected behavior, you may want to run it immediately using Scheduler.immediate as follows:

var source=Rx.Observable
.range (1, 3, Rx.Scheduler.immediate)
.flatMap(function(v){
    return Rx.Observable.range(1,3,Rx.Scheduler.immediate);
})
.subscribe(function(v){
    console.log(v)
});

Note:
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/schedulers/scheduler.md


2022-09-30 16:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.