Input Observable stream: The information is retrieved from an observable stream, which stems from a REST request for various projects. This data is obtained in the form of Observable<Project[]>.
const project1: Project = {
id: 1,
title: 'zebra',
rootId: 1,
}
const project2: Project = {
id: 2,
title: 'algebra',
rootId: 2,
}
const project3: Project = {
id: 3,
title: 'Bobcats',
rootId: 1,
}
const project4: Project = {
id: 4,
rootId: 2,
}
const project5: Project = {
id: 5,
title: 'Marigolds',
rootId: 1,
}
const project6: Project = {
id: 6,
title: 'whatever',
rootId: null,
}
const project7: Project = {
id: 7,
title: 'peppercorns',
rootId: null,
}
let groupProjects: Observable<ProjectSummary[]>
= retrieveGroupedProjects(of([project1, project2, project3, project4, project5, project6, project7]]));
retrieveGroupedProjects(projects$: Observable<ProjectSummary[]>): Observable<ProjectSummary[]> {
const timer$ = timer(5000);
const gatheredData = projects$.pipe(takeUntil(timer$), flatMap(projects => projects));
const segregatedObservables = gatheredData.pipe(
groupBy(projects => projects.rootId),
tap( a => console.log('grouped by:' + a.key))
);
const mergedResults = segregatedObservables.pipe(
mergeMap(a => a.pipe(toArray())),
shareReplay(1),
tap( a => console.log('final results:' + JSON.stringify(a)))
);
return mergedResults;
}
The expected output is:
Object{ //Root of 1
id: 1,
title: 'zebra',
rootId: null
}
Object{
id: 3, //child of 1
title: 'Bobcats',
rootId: 1
}
Object{
id: 5, //child of 1
title: 'Marigolds',
rootId: 1
}
Object{
id: 2, //root of 2
title: 'algebra',
rootId: 2
}
Object{
id: 4, //child of 2
title: 'dogs',
rootId: 2
}
Object{
id: 6, //unaffiliated
title: 'whatever',
rootId: null
}
Object{
id: 7, //unaffiliated
title: 'peppercorns',
rootId: null
}
The condition specifies that groups assigned with a rootId should be displayed before their children (children come after their root) and unattached instances are grouped together. Root elements are recognized when id = rootId, child elements are identified when rootId != null && id != rootId. Unattached instances have a null root id.
Currently, only the final group is being broadcasted. Is there a way to return an observable that transmits all groups and maintains the correct sequence? --appreciate it