带有区间变量的 rxjs 无限循环
rxjs infinite loop with an interval variable
我想使用 rxjs Observable 以区间变量进行无限循环
所以我试图在 rxjs
中重写这个函数
takeAWalk(player){
setTimeout(() => {
console.log("Player is walking...");
takeAWalk(player);
}, getRandomDelayBetween(1000, 2500));
}
我试过了
Observable
.timer(0, getRandomDelayBetween(1000, 2500))
.take(10)
.timeInterval()
.subscribe(res=>{
console.log("player is walking ...");
});
但问题是这个有限到10,区间是常量(getRandomDelayBetween
只调用了一次)
我应该使用哪些运算符来产生与 takeAWalk
函数相同的功能?
在 rxjs 中有很多种写法,你可以试试这样:
Rx.Observable.of(null)
.concatMap(() => Rx.Observable.timer(Math.random() * 1500))
.do(() => console.log("player is walking ..."))
.repeat() // optionally .repeat(10)
.subscribe();
只是为了扩展 expand
:')
这是我创建的一个 runWhile 函数,它的作用类似于 while 循环,具有奖励间隔值,用于延迟每个循环之间的事件。
直到条件为假,它才会继续循环。
import { EMPTY, Observable, of, OperatorFunction } from 'rxjs';
import { delay, expand, filter, flatMap, mapTo } from 'rxjs/operators';
/**
* Like a while loop for RxJS,
* while (condition()) { doFn() }
*
* @param condition
* @param doFn
* @param interval
* @param initialValue
*/
export function runWhile<T = any> (
condition : () => boolean,
doFn : () => Observable<T>,
interval = 0,
initialValue = null,
) : OperatorFunction<T, T> {
return flatMap<T, T>((initial) => {
return of(condition())
.pipe(
expand((cond) => {
if (cond === false) {
return EMPTY;
}
return doFn().pipe(delay(interval), mapTo(condition()));
}),
filter(cond => cond === false),
mapTo(initial),
);
});
}
有关其工作原理的示例,请参阅此代码笔。
CodePen
我想使用 rxjs Observable 以区间变量进行无限循环 所以我试图在 rxjs
中重写这个函数takeAWalk(player){
setTimeout(() => {
console.log("Player is walking...");
takeAWalk(player);
}, getRandomDelayBetween(1000, 2500));
}
我试过了
Observable
.timer(0, getRandomDelayBetween(1000, 2500))
.take(10)
.timeInterval()
.subscribe(res=>{
console.log("player is walking ...");
});
但问题是这个有限到10,区间是常量(getRandomDelayBetween
只调用了一次)
我应该使用哪些运算符来产生与 takeAWalk
函数相同的功能?
在 rxjs 中有很多种写法,你可以试试这样:
Rx.Observable.of(null)
.concatMap(() => Rx.Observable.timer(Math.random() * 1500))
.do(() => console.log("player is walking ..."))
.repeat() // optionally .repeat(10)
.subscribe();
只是为了扩展 expand
:')
这是我创建的一个 runWhile 函数,它的作用类似于 while 循环,具有奖励间隔值,用于延迟每个循环之间的事件。
直到条件为假,它才会继续循环。
import { EMPTY, Observable, of, OperatorFunction } from 'rxjs';
import { delay, expand, filter, flatMap, mapTo } from 'rxjs/operators';
/**
* Like a while loop for RxJS,
* while (condition()) { doFn() }
*
* @param condition
* @param doFn
* @param interval
* @param initialValue
*/
export function runWhile<T = any> (
condition : () => boolean,
doFn : () => Observable<T>,
interval = 0,
initialValue = null,
) : OperatorFunction<T, T> {
return flatMap<T, T>((initial) => {
return of(condition())
.pipe(
expand((cond) => {
if (cond === false) {
return EMPTY;
}
return doFn().pipe(delay(interval), mapTo(condition()));
}),
filter(cond => cond === false),
mapTo(initial),
);
});
}
有关其工作原理的示例,请参阅此代码笔。 CodePen