RxJS根据列表过滤列表

时间:2015-09-10 23:14:27

标签: reactive-programming observable rxjs

如果我有一个参数数量变化(或可以更新)的列表:

SomeDynamicListofPreferences = [
 'Chocolate',
 'Strawberry',
 'Vanilla'
];

什么(如果有的话)是一种很好的RxJS方法,可以根据主要源流动态过滤匹配列表?

StockedFlavors = [
 'Almond Mocha',
 'Banana',
 'Butter Pecan',
 'Chocolate',
 'Coconut Cream',
 ...
 'Strawberry',
 'Vanilla'
];

Ex:根据我迄今所学到的,一种可能性是:

let dynamicPreferences = Rx.Observable.fromArray(SomeDynamicListofPreferences);
let StockedStream = Rx.Observable.fromArray(StockedFlavors);

let PrefMatches = StockedStream.filter((flavor) => 
  dynamicPreferences.includes(flavor) ).
subscribe((x) => { if(x){  /*...do stuff */ }});

“includes”运算符感觉就像循环中的循环。我可以看到另一个迭代原始SomeDynamicListofPreferences以生成单个filterStream的场景。

非常感谢任何有关技术和/或规模的帮助。

1 个答案:

答案 0 :(得分:0)

这适合我... ymmv

function deferSource(source) {
  // wrapping in the defer gives us a unique snowflake observable
  return Rx.Observable.defer(function() {
    // your returned observable may vary as well... 
    return Rx.Observable.fromArray(source);
  })
}

// your observable sources may vary
var preferenceList = [
 'Chocolate',
 'Strawberry',
 'Vanilla'
];

var flavorList = [
 'Almond Mocha',
 'Banana',
 'Butter Pecan',
 'Chocolate',
 'Coconut Cream',
 'Strawberry',
 'Vanilla Bean'
];

var prefrence$ = deferSource(preferenceList)
var flavor$ = deferSource(flavorList);

function curryQuery(static$source) {
  return function querySourceForResults(dynamic_element) {
    return static$source
      .filter(function(static_element){
        return static_element.includes(dynamic_element)
      })
  }
}

prefrence$.flatMap(curryQuery(flavor$)).subscribe(logger('result'))