29er
29er

Reputation: 9005

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

HI I have 3 Subjects ( they could be Observables )

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

let's say these subjects contain this data

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

I want to create an observable (mergedObservable) that combines the latest from these 3 observables, merges them into one array, where the result is one array like this: ['1','2','3','7','4']

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

I am struggling with how to make this 'mergedObservable'. I have tried something like combineLatest(arr1$,arr2$,arr3$) , but I still need to 'chain' more functionality that will merge the 3.

Thanks!

Upvotes: 1

Views: 1812

Answers (2)

vbmaster
vbmaster

Reputation: 1

fake, fake1, api are different arrays or sources.

 combineLatest(fake, fake1, api)
    .pipe(
      map(([f,f1, apis])=>
       {
         return ([...f, ...f1, ...apis]);
       }
      )
   )
    .subscribe((data) => {
        console.log(data);
      });

Upvotes: 0

cartant
cartant

Reputation: 58400

combineLatest takes an optional project function that can be used to modify the combined value.

You can specify a project function that uses Array.prototype.reduce to flatten the arrays into a 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@5/bundles/Rx.min.js"></script>

Upvotes: 5

Related Questions