6

私はこれを理解するのに少し苦労しています。Observable で switchMap オペレーターを使用すると、期待どおりにすべての値が出力されます。

Observable.from([1, 2, 3, 4, 5])
    .do(console.log)
    .switchMap(i => Observable.of('*' + i))
    .do(console.log)
    .subscribe();

結果:

1
*1
2
*2
3
*3
4
*4
5
*5

しかし、Observable を Promise に置き換えると、別の動作になります。

Observable.from([1, 2, 3, 4, 5])
    .do(console.log)
    .switchMap(i => new Promise((resolve) => resolve('*' + i)))
    .do(console.log)
    .subscribe();

結果:

1
2
3
4
5
*5
4

1 に答える 1

3

This works as expected. The unexpected behaviors as you said is because Observable.from and Observable.of are always strictly synchronous while new Promise necessarily doesn't (I'm not sure about the specification so maybe that's what Promise has to do in all browsers).

Anyway you can force Observable.from emit asynchronously by passing the async Scheduler.

import { Observable } from 'rxjs';
import { async } from 'rxjs/scheduler/async';

Observable.from([1, 2, 3, 4, 5], async)
    .do(console.log)
    .switchMap(i => new Promise((resolve) => resolve('*' + i)))
    .do(console.log)
    .subscribe();

Now every emission is in a new frame just like Promise and the output is as you expected.

See live demo (open console): https://stackblitz.com/edit/rxjs5-gfeqsn?file=index.ts

于 2018-02-17T16:48:47.783 に答える