Concat list and observable list

Viewed 134

Let's say I have 3 lists. Two of them are basic lists while the last one is an observable.

The issue is I now want to merge a non-observable list into the observable one.
Right now I do something like this but I feel like it's "against observables' nature"

listToMerge = []
listObs$: BehaviorSubject<[]> = new BehaviorSubject([]);
listObsCopy = []

I already added some elements in the listObs with the next method

listObs$.next(someStuff);
listObsCopy = somestuff;

Here is my attempt to merge them.

listToMerge = listObsCopy.concat(someOtherStuff);
listObs$.next(listToMerge as any);
2 Answers

Is this what you're looking for? It will merge all arrays into a single one using RxJS.

    import { BehaviorSubject, merge } from 'rxjs';
    import { concatAll, take, tap, toArray } from 'rxjs/operators';

    // Subject (and Observable with take(1) to force completion.)
    let listSubject: BehaviorSubject<string[]> = new BehaviorSubject<string[]>(['B1', 'B2']);
    let listObs$ = listSubject.asObservable().pipe(take(1));

    // List to Merge 
    let listToMerge = ['1', '2'];

    let mergedObs$ = merge(listToMerge, listObs$).pipe(concatAll(), toArray());

    mergedObs$.subscribe((value) => console.log('merged array:', value));

https://stackblitz.com/edit/typescript-ukxwep?file=index.ts

The trick is in using concatAll() operator to flatten all arrays and then use toArray() operator to make 1 array out of that.

Note that I've added take(1) to the observable for the subject. The subscribe will only start when the Observable ends.

Related