我正在尝试显示前三个数字,每个数字延迟1秒,第四个数字延迟4秒。不幸的是,我的代码在1秒内显示了四个数字
import { from, of, race, timer, interval } from 'rxjs';
import { groupBy, mergeMap, toArray, map,merge, reduce, concatMap, delay, concat, timeout, catchError, take } from 'rxjs/operators';
const obs$ = from([1,2,3]).pipe(concatMap(a => of(a).pipe(delay(1000))));
const obs2$ = of(4).pipe(delay(4000));
const result$ = obs$.pipe(merge(obs2$));
const subscribe = result$.subscribe(val => console.log(val));
它显示 1234 |
而不是 123 ---- 4 |
这个问题完全适合初学者学习rxjs,并且已经在https://stackblitz.com上进行了测试
答案 0 :(得分:2)
方法1
merge
运算符同时同时订阅了可观察的(obs$
和obs2$
)。因此,您从代码中获得的结果可能解释如下:
obs$ -----1-----2-----3
obs2$ -----------------------4
result$ -----1-----2-----3-----4
通过将第二个参数设置为1(默认为merge
),强制Number.POSITIVE_INFINITY
一次只订阅一个可观察的对象,可以实现您的目标,如下所示:
const obs$ = from([1,2,3]).pipe(concatMap(a => of(a).pipe(delay(1000))));
const obs2$ = of(4).pipe(delay(4000));
// Provide the concurrency (second) argument as 1
const result$ = obs$.pipe(merge(obs2$, 1));
const subscribe = result$.subscribe(val => console.log(val));
方法2
使用concat
代替merge
:
const obs$ = from([1, 2, 3]).pipe(concatMap(a => of(a).pipe(delay(1000))));
const obs2$ = of(4).pipe(delay(4000));
const result$ = concat(obs$, obs2$);
const subscribe = result$.subscribe(val => console.log(val));
方法3
否则,您只需使用concatMap
的第二个参数,即发射项目的索引(从0开始)。
const obs$ = from([1, 2, 3, 4]);
const delayed$ = obs$.pipe(
concatMap((value, index) => {
if (index <= 2) {
// Delay the first 3 items by 1 sec
return of(value).pipe(delay(1000));
} else {
// Delay other items (here the 4th item) by 4 sec
return of(value).pipe(delay(4000));
}
})
);
delayed$.subscribe(x => console.log(x));