RxJS 如何将流映射到最新的不同流?

RxJS How to map a stream to the latest of a different stream?

我目前正在使用 Cycle.js,我正在尝试在提交表单时获取文本输入流。例如:

const textChange$ = DOMSource.select('input').events('change');
const textValueSubmit$ = DOMSource.select('form').events('submit')
    .do(ev => ev.preventDefault());

我想此时我需要合并流,但我只关心最新的文本值(当用户提交表单时)。处理这种情况的适当方法是什么?

您也可以使用 sample() 来避免创建额外的功能,我相信这就是您正在寻找的功能

const textChange$ = DOMSource.select('input').events('change')
  .pluck('target', 'value')
const submit$ = DOMSource.select('form').event('submit')
  .do(ev => ev.preventDefault)
const textValueSubmit$ = textChange$.sample(submit$)

除了当前的答案,您还可以使用 withLatestFrom。请注意 combineLatestwithLatestFrom 语义在细微之处有所不同:

  • combineLatest 将在其中一个组合源发出一个值时发出一个值(只要每个源可观察序列都发出至少一个元素
  • withLatestFrom 仅当组合源发出值时才会发出值

所以你可以这样做:

const textChange$ = DOMSource.select('input').events('change')
  .pluck('target', 'value')
const submit$ = DOMSource.select('form').event('submit')
  .do(ev => ev.preventDefault)
const textValueSubmit$ = submit$.withLatestFrom(textChange$, function (submit, textChange){...});

即使这不涵盖比您的特定用例更多的内容(在这里您不关心提交事件传递的值,因此建议 sample 也可以正常工作),它仍然是很高兴在另一个类似的未来用例中牢记这两个运算符。

最后,combineLatest 在这种情况下真的适合您吗?似乎每次 textChange$ 触发时你都会有一个 textValueSubmit$ 发射。这是预期的行为吗?