RxJS proper way to merge 3 arrays into one, as an Observable -


hi have 3 subjects ( observables )

 const arr1$ = new behaviorsubject([])  const arr2$ = new behaviorsubject([])  const arr3$ = new behaviorsubject([]) 

let's these subjects contain data

arr1 = ['1','2'],  arr2 = ['3','7'],  arr3 = ['4'] 

i want create observable (mergedobservable) combines latest these 3 observables, merges them 1 array, result 1 array this: ['1','2','3','7','4']

so can achieve  this.mergedobservable.subscribe( mergedarray => {      console.log(mergedarray) }) // ['1','2','3','7','4'] 

i struggling how make 'mergedobservable'. have tried combinelatest(arr1$,arr2$,arr3$) , still need 'chain' more functionality merge 3.

thanks!

combinelatest takes optional project function can used modify combined value.

you can specify project function uses array.prototype.reduce flatten arrays single array:

const arr1$ = new rx.behaviorsubject(['1','2']);  const arr2$ = new rx.behaviorsubject(['3','7']);  const arr3$ = new rx.behaviorsubject(['4']);    rx.observable    .combinelatest(      arr1$, arr2$, arr3$,      (...arrays) => arrays.reduce((acc, array) => [...acc, ...array], [])    )    .subscribe(value => console.log(value));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs/bundles/rx.min.js"></script>


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -