【问题标题】:rxjs - Iterate back in Observablesrxjs - 在 Observables 中迭代
【发布时间】:2018-08-24 02:43:48
【问题描述】:

每次生成新值时,我都需要将其与所有以前的值进行比较,并且只有满足条件时才会将其添加到流中。

如何用 observables 做到这一点?

【问题讨论】:

  • 您需要执行哪种类型的比较?例如,如果您想检查该值是否是以前从未发出过的新值,则可以使用运算符distinct。如果您提供更多详细信息,也许我们可以为您提供更多帮助。
  • 不同的不适用。值是字符串,比较函数是相似度

标签: rxjs rxjs5 angular2-observables rxjs-lettable-operators


【解决方案1】:

这是一个例子,可能有点复杂,应该做一些类似于你正在寻找的事情

import {Observable} from 'rxjs';

const values = ['aa', 'ab', 'ac', 'ba', 'db', 'bc', 'cc', 'cb', 'cc']

Observable.from(values)
// accumulate all previous values into an array of strings
.scan((previousValues, thisValue) => {
    previousValues.push(thisValue)
    return previousValues
}, [])
// create an object with the previous objects and the last one
.map(previousValues => {
    const lastValue = previousValues[previousValues.length - 1]
    return {previousValues, lastValue}
})
// filters the ones to emit based on some similarity logic
.filter(data => isNotSimilar(data.lastValue, data.previousValues))
// creates a new stream of events emitting only the values which passed the filter
.mergeMap(data => Observable.of(data.lastValue))
.subscribe(
    value => console.log(value)
)

function isNotSimilar(value: string, otherValues: Array<string>) {
    const otherValuesButNotLast = otherValues.slice(0, otherValues.length - 1);
    const aSimilar = otherValuesButNotLast.find(otherValue => otherValue[0] === value[0]);
    return aSimilar === undefined;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多