一、代码:
Observable
// Turn an array, promise, or iterable into an observable.
.from(localArray)
// Map values to inner observable, subscribe and emit in order.
.concatMap((arrayElement: any) => {
// Returning an observable that returns a value
return Observable.of(arrayElement);
})
// Emit only values that meet the provided condition.
.filter((value: any) => {
return value === 'Some condition';
})
// Reduces the values from source observable to a single value that's emitted when the source completes.
// If you need the current accumulated value on each emission, try scan - https://www.learnrxjs.io/operators/transformation/scan.html
// The second argument here is the seed, the initial value provided the first time reduce is called. (In this case, an empty array)
.reduce((filteredValue: any, accumulatedFilteredValues: any[]) =>{
accumulatedFilteredValues.push(filteredValue);
return accumulatedFilteredValues;
}, [])
.subscribe((filteredValueArray: any[]) => {
// Do something with the array of ordered, filtered values
});
首先,我使用from 创建了一个可观察对象来发射localArray 中的每个arrayElement。
当每个arrayElement 发出时,我将arrayElement 映射到将返回一些value 的Observable(在这种情况下我只返回arrayElement)。我正在使用concatMap,因为它会订阅内部可观察对象并在完成后发出它们的值,按照发出的顺序。
我使用filter 只发出满足条件的value。过滤器采用返回true 或false 的函数。如果返回true,则会发出value。
最后,我使用reduce 收集filteredValue 并将其添加到accumulatedFilteredValues 的数组中。 Reduce 接受一个函数作为它的第一个参数,一个可选的种子作为它的第二个参数。
传递给reduce的函数接收最近的发射(filteredValue)作为其第一个参数,并接收一个累积值作为第二个参数(空数组[])
将这些运算符应用于发出的值后,传递给 subscribe 的函数会接收一个数组,其中包含来自localArray 的过滤后的有序项。
learn-rxjs 是一个优秀的 RxJS 资源,包含各种运算符的示例和描述。
如果您使用的是 RxJS >= 5.5,请考虑改用 pipeable operators。在这种情况下,代码看起来会更接近于这个:
from(localArray).pipe(
concatMap((arrayElement: any) => {
return Observable.of(arrayElement);
}),
filter(value => {
return value === 'Some condition';
}),
reduce((filteredValue: any, accumulatedFilteredValues: any[]) => {
accumulatedFilteredValues.push(filteredValue);
return accumulatedFilteredValues;
}, [])
)
.subscribe((filteredValueArray: any[]) => {
// Do something with the array of ordered, filtered values
});