Rxjs:rxjs中是否有任何运算符可以在未映射数组时执行?

时间:2017-03-30 12:39:15

标签: rxjs observable

我有一个静态数组

var array=[{name:'test',id:2106},{name:'test2',id:2107},{name:'test3',id:2108}];

I have a selected name
var selName='test4';

当selName与数组对象中的任何名称都不匹配时,我想执行函数。

让功能

function runtesting(){

}

如果selName与数组中的名称匹配,我想显示一个警告框。

我们如何使用Rxjs运算符实现这一目标?

1 个答案:

答案 0 :(得分:0)

const array$ = Observable.of([
 {name:'test', id:2106},
 {name:'test2', id:2107},
 {name:'test3', id:2108}
])

const selectedName$ = new BehaviorSubject('test4')

然后结合两者:

const runTestingSub = Observable
  .combineLatest(array$, selectedName$)
  .map(([arr, name]) => !arr.some(item => item.name === name))
  .filter(Boolean) // Emit only if there is no name in array
  .subscribe(runTesting) // runTesting runs only if there is no obj with name

通过将此数组存储为键值构造,您甚至可以使其更高效:

{
   test: { name: 'test', id: 2106 },
   test2: { name: 'test2', id: 2107 }
}

甚至是JavaScript / Immutable Map。例如:

const arrayReduced$ = Observable
  .of([
     {name:'test', id:2106},
     {name:'test2', id:2107},
     {name:'test3', id:2108}
  ])
  .scan((acc, curr) => Object.assign({}, acc, {
    [curr.name]: curr
  }), {})

然后runTestingSub将如下所示:

const runTestingSub = Observable
  .combineLatest(array$, selectedName$)
  .map(([keyValueObj, name]) => !keyValueObj[name])
  .filter(Boolean)
  .subscribe(runTesting)