【问题标题】:RxJS Observable reset timeoutRxJS Observable 重置超时
【发布时间】:2017-03-23 10:41:03
【问题描述】:

是否可以在设置了另一个超时后重置/增加 Observable 的超时?在以下示例中,超时 5 应被超时 9999 覆盖,但这不起作用:

var source = Rx.Observable
.return(42)
.delay(1000)
.timeout(5)
.timeout(9999); // this statement should override the previous set timeout of 5 MS, but actually it does not

var subscription = source.subscribe(
function (x) {
    console.log('Next: ' + x);
},
function (err) {
    console.log('Error: ' + err);   
},
function () {
    console.log('Completed');   
});

是否有可能覆盖已设置的超时?

【问题讨论】:

  • 您想更改超时时间时可以重新订阅吗?然后你可以在订阅时间做它,比如 source.timeout(timeoutVariable).subscribe(....),并取消订阅 - 当 timeoutVariable 更改时重新订阅....实际上,有没有办法将此更改事件放入流中?编辑 - 是的,提交可能的答案

标签: timeout rxjs observable


【解决方案1】:

简答:据我所知,没有“合法”解决方案。


Hacky answer:您可以连接到timeout-ed 流的source 并设置您自己的超时,请参阅下面的示例如何做到这一点。 但是,我建议您在任何严肃的项目中这样做 - 我确信应该有另一种解决方案来解决您的问题。

var base = Rx.Observable
.return(42)
.delay(1000)
.timeout(1);

var patched = base.source.timeout(2000);

var subscription = patched.subscribe(
function (x) {
    console.log('Patched Next: ' + x);
},
function (err) {
    console.log('Patched Error: ' + err);   
},
function () {
    console.log('Patched Completed');   
});

var subscription = base.subscribe(
function (x) {
    console.log('Base Next: ' + x);
},
function (err) {
    console.log('Base Error: ' + err);   
},
function () {
    console.log('Base Completed');   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>

【讨论】:

    【解决方案2】:

    如果你用一个主题来表示你的超时值呢?

    timeoutSubject = new Rx.ReplaySubject(1);
    timeoutSubject
        .asObservable()
        .switchMap((v) => source.timeout(v))
        .subscribe((r) => console.log(r));
    
    timeoutSubject.next(5);
    timeoutSubject.next(9999);
    

    switchMap 应该处理每个超时值的取消订阅/重新订阅。

    【讨论】:

      猜你喜欢
      • 2021-02-21
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多