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);
CodePudding user response:
You can easily create an observable from your array to then concat them using the from()
function:
https://www.learnrxjs.io/learn-rxjs/operators/creation/from
const arraySource = from([1, 2, 3, 4, 5]);
const arraySource2 = from([6, 7, 8]);
arraySource.concat(arraySource2).subscribe()
CodePudding user response:
Is this what you're looking for? It will merge all arrays into a single one using RxJS.
import { of, BehaviorSubject, merge } from 'rxjs';
import { concatAll, take, tap, toArray } from 'rxjs/operators';
let listToMerge = [];
let listSubject: BehaviorSubject<string[]> = new BehaviorSubject<string[]>(['B1','B2',]);
let listObs$ = listSubject.asObservable().pipe(take(1));
let listObsCopy = [];
// Give some content
listObsCopy = ['Three', 'Four'];
listToMerge = ['1', '2'];
let mergedArray$ = merge(of(listObsCopy), of(listToMerge), listObs$).pipe(
concatAll(),
toArray(),
);
mergedArray$.subscribe((value) => console.log('merged array:', value));
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.