RxJS超时无效

时间:2017-02-24 18:50:17

标签: javascript timeout rxjs

我尝试在超过3秒的时间内退出Observable流。问题是,当我复制并粘贴相同的值几次时,distinctUntilChanged运算符不会让输入流通过。所以如果没有字符串流传递它,我想超时。这就是我所拥有的。

        import { Subject } from "rxjs/Subject";
        import "rxjs/add/operator/filter";
        import "rxjs/add/operator/debounceTime";
        import "rxjs/add/operator/distinctUntilChanged";
        import "rxjs/add/operator/switchMap";
        import "rxjs/add/operator/timeout";

        this._searchSubject
        .filter(val => val.length > 0)
        .debounceTime(500)
        .distinctUntilChanged()
        .timeout(3000)
        .switchMap(userSearchInput => {
            ...api call that returns Promise
        })
        .subscribe(searchResults => {
            ...do stuff with the result
        });

1 个答案:

答案 0 :(得分:3)

超时会引发TimeoutError,您是否正在处理此错误?

Rx.Observable.from(new Promise(resolve => setTimeout(resolve, 1000)))
  .timeout(500)
  .subscribe(console.log, ({ message }) => console.error(message));

或者您可以使用timeoutWith& Rx.Observable.empty()结束流:

Rx.Observable.from(new Promise(resolve => setTimeout(resolve, 1000)))
  .timeoutWith(500, Rx.Observable.empty())
  .subscribe(null, null, () => console.log('done'));