Rxjs5 RepeatWhen在组合中可观察到。of(x)具有意外行为

Rxjs5 RepeatWhen在组合中可观察到。of(x)具有意外行为,rxjs5,reactive,Rxjs5,Reactive,我在Observable.of()和repeatWhen中出现意外行为。我想知道这是不是正确的行为,为什么 const value = 5; let variable = 0; const getValue = () => { variable = variable + 1; return value * variable; } function test () { Observable.of(getValue()) .repeatWhen(ob

我在Observable.of()和repeatWhen中出现意外行为。我想知道这是不是正确的行为,为什么

const value = 5;
let variable = 0;

const getValue = () => {
    variable = variable + 1;
    return value * variable;
}

function test () {
    Observable.of(getValue())
        .repeatWhen(obs => obs.delay(1000))
        .subscribe(value => console.log(value);
}
预计:510520

结果:5


显然,Observable.of()返回的值将被重新用于每个后续订阅。如何,为什么?

问题在于
值的使用。您正在更改
变量
而不是
(该值在两个范围内可用,即全局范围和更近范围)

要解决此问题,请更改
getValue
的定义,如下所示:

const getValue = () => {
    variable = variable + 1;
    value = value * variable;
    return value;
}
因此,更正后的代码如下所示:

const value = 5;
let variable = 0;

const getValue = () => {
    variable = variable + 1;
    value = value * variable;
    return value;
}

function test () {
    Observable.of(getValue())
        .repeatWhen(obs => obs.delay(1000))
        .subscribe(value => console.log(value);
}

问题是,
getValue()
只会立即计算一次。这与rxjs无关,只是Javascript的工作方式。您需要在每次重试时对其进行评估,您可以使用
延迟

Observable.defer(() => Observable.of(getValue()))
  .repeatWhen(obs => obs.delay(1000))
  .subscribe(console.log);

@Elias我们正在打印
变量
而不是
。变量将返回1、2、3、4、5,您可以看到getValue()的作用。