rxjs - 迭代回Observables

时间:2018-03-15 10:21:55

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

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

如何通过观察者来完成这项工作?

1 个答案:

答案 0 :(得分: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;
}