I'm stuck here right now I hope someone can help me :-)
following scenario:
I have two streams which transfer the same data type. The first stream provides initial data (REST call) and completes afterwards. The second stream gets its data via websocket and does not complete.
const mockData: User[] = [
{ id: '1', status: 'active' },
{ id: '2', status: 'inactive' },
{ id: '3', status: 'active' }
];
const initial$: Observable<User[]> = of(mockData);
const sub$: BehaviorSubject<User[]> = new BehaviorSubject(mockData);
const dynamic$ = sub$.asObservable();
Now I want to merge both streams and create two new streams based on a filter criterion, one for the active and one for the deactivated users.
const merged$ = merge(initial$, dynamic$).pipe(
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))
);
const grouped$ = merged$.pipe(
mergeMap((users: User[]) => from(users)),
tap(a => console.log('Before group by', a)),
groupBy(item => item.status),
tap(a => console.log('After group by', a.key)),
mergeMap(group => zip(of(group.key), group.pipe(toArray()))),
tap(a => console.log('after merge map', a))
);
const activeByGrouped$ = grouped$.pipe(
filter(([key]) => key === 'active'),
map(([key, value]) => value)
);
activeByGrouped$.subscribe(a => console.log('final subscribe', a));
The whole thing works if both streams complete, but not if one is open. Attached is a stackblitz for better understanding.
>> stackblitz https://stackblitz.com/edit/typescript-ixc3nu <<