使可观察的间隔以延迟时间(以秒为单位)发射整数和每个新值的最佳方法是什么?
interval().subscribe(v => console.log(v))
预期:
1 --- after 1 second
2 --- 2 seconds after 1 was emitted
...
37 --- 37 seconds after 36 was emitted
...
我已经为您创建了沙箱-https://stackblitz.com/edit/rxjs-task-delay?file=index.ts
答案 0 :(得分:1)
当我们使用mergeMap时,所有内部可观测对象在创建后立即被订阅,因此我们不会得到越来越大的时间间隔,因为interval
每秒发射一次 ,因此所有内部可观测对象在源发出后立即订阅:
source.pipe(
mergeMap(num => of(num).pipe(
delay(num * 1000)
)
)
emits 1 after 1 sec., inner waits 1 sec
emits 2 after 1 sec., inner waits 2 sec (1 sec already passed)
emits 3 after 1 sec., inner waits 3 sec (2 secs already passed)
但是在先前完成之前,concatMap
内部没有被订阅:
source.pipe(
concatMap(num => of(num).pipe(
delay(num * 1000)
)
)
答案 1 :(得分:1)
我已经完成了BehaviorSubject
:
import { BehaviorSubject} from 'rxjs';
const sub = new BehaviorSubject(1);
sub.subscribe( val => {
console.log( val);
setTimeout( () => {sub.next(val+1);}, val*1000);
});