【问题标题】:RxJS: Timeout without Error/CompleteRxJS:超时无错误/完成
【发布时间】:2016-07-07 09:27:23
【问题描述】:

有一个 websocket 连接,如果连接是直立的,我会尝试获取信息。我尝试用 RxJS 和一个间隔来做。问题是,在一次超时后流结束,我希望间隔之后继续,以便我可以查看它是否已经重新连接。

    function listenToConnectionLost () {
        return rx.Observable
            .interval(5000) // every 5 seconds
            .flatMap(tryPing)
            .distinctUntilChanged()
            // so I want to have either "connected" or "timeout" here
            // onNext I want to handle the different outputs 
        ;
    }

    function tryPing () {
        var pingPromise = getPingPromise();
        var pingObservable = rx.Observable
            .fromPromise(pingPromise)
            .timeout(5000)
            .catch(Rx.Observable.just('timeout')) // catches error, but
                                                  // completes the stream
        ;

        return pingObservable;
    }

    function getPingPromise () {
        // returns a promise, which resolves when connection is upright
    }

这里我还有一个带有“伪造”间隔的实时示例:http://jsbin.com/gazuvu/4/edit?js,console

谢谢!

【问题讨论】:

    标签: javascript timeout rxjs


    【解决方案1】:

    显然上面发布的代码正在运行,因为完成的流将被馈送到listenToConnectionLost 中的flatMap。我通过将以下代码插入getPingPromise 来测试它。

    function getPingPromise () {
      if(Math.random() < 0.5) {
        return $q.when('connected'); // resolves immediately
      }
      else {
        return $q.defer().promise; // never resolves, triggers timeout
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多