如何中止@ cycle / http驱动程序的调用?

时间:2016-06-26 10:05:03

标签: javascript rxjs cyclejs

我对整个Cycle.js / RxJS生态系统都很陌生,希望有人能指导我完成自it looks like doable somehow以来正在进行的ajax调用的过程。

使用此search-github-user分配一个小例子真是太棒了。

为了避免SO狂热者的贬低,我在这里添加了一个副本:

import Cycle from '@cycle/core';
import {Observable} from 'rx';
import {div, label, input, hr, ul, li, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';

function main(sources) {
  // Requests for Github repositories happen when the input field changes,
  // debounced by 500ms, ignoring empty input field.
  const searchRequest$ = sources.DOM.select('.field').events('input')
    .debounce(500)
    .map(ev => ev.target.value)
    .filter(query => query.length > 0)
    .map(q => ({
      url: 'https://api.github.com/search/repositories?q=' + encodeURI(q),
      category: 'github',
    }));

  // Requests unrelated to the Github search. This is to demonstrate
  // how filtering for the HTTP response category is necessary.
  const otherRequest$ = Observable.interval(1000).take(2)
    .map(() => 'http://www.google.com');

  // Convert the stream of HTTP responses to virtual DOM elements.
  const vtree$ = sources.HTTP
    .filter(res$ => res$.request.category === 'github')
    .flatMap(x => x)
    .map(res => res.body.items)
    .startWith([])
    .map(results =>
      div([
        label({className: 'label'}, 'Search:'),
        input({className: 'field', attributes: {type: 'text'}}),
        hr(),
        ul({className: 'search-results'}, results.map(result =>
          li({className: 'search-result'}, [
            a({href: result.html_url}, result.name)
          ])
        ))
      ])
    );

  const request$ = searchRequest$.merge(otherRequest$);

  return {
    DOM: vtree$,
    HTTP: request$
  };
}

Cycle.run(main, {
  DOM: makeDOMDriver('#main-container'),
  HTTP: makeHTTPDriver()
});

更新

感谢@ user3743222指出主分支上的更改,似乎作者已发布新版本,现在中止部分为here

2 个答案:

答案 0 :(得分:1)

我对新代码一点都不熟悉,但在旧代码中,似乎http驱动程序为每个请求返回一个observable。如果在满足请求之前该可观察终止/取消订阅,则该请求被中止。所以基本上,调用API,获取封​​装请求结果的observable,并在想要中止时终止该observable。

如何随意终止观察?你可以使用 takeUntil(someOtherStream)如果您有其他信号流中止。

答案 1 :(得分:1)

在当前版本中,所有response$流都会立即被收听,因此它们永远不会在请求到来之前终止,并且中止无效。那里有一个issue