rxjs - 在 Observables 中迭代
rxjs - Iterate back in Observables
每次生成新值时,我都需要将它与所有以前的值进行比较,只有满足条件时才会将其添加到流中。
如何使用 observables 来做到这一点?
这是一个示例,可能有点复杂,它应该与您正在查找的内容类似
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;
}
每次生成新值时,我都需要将它与所有以前的值进行比较,只有满足条件时才会将其添加到流中。
如何使用 observables 来做到这一点?
这是一个示例,可能有点复杂,它应该与您正在查找的内容类似
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;
}