I'm encountering an issue with rxjs.
I have a function that is supposed to:
- Take a list of group IDs, such as:
of(['1', '2'])
- Fetch the list of chats for each ID
- Return a merged list of chats
However, when it reaches the toArray method, nothing happens and no result is produced.
Code
get chats$(): Observable<Chat[]> {
return of(['1', '2']).pipe(
filter(groupIds => !!groupIds && groupIds.length > 0),
switchMap(groupIds => groupIds),
switchMap(groupId => getGroupChats(groupId)), // fetch list of chats for the group id
toArray(),
map(doubleList => {
return ([] as Chat[]).concat(...doubleList); // merge chat lists
})
);
}
I also tried the following approach:
get chats$(): Observable<Chat[]> {
return of(['1', '2']).pipe(
filter(groupIds => !!groupIds && groupIds.length > 0),
map(groupIds =>
groupIds.map(groupId => getGroupChats(groupId))
),
switchMap(chatList$ =>
forkJoin(chatList$).pipe(
map(doubleList => {
return ([] as Chat[]).concat(...doubleList);
})
)
)
);
}
Test
The test response indicates:
Error: Timeout - Async callback was not invoked within 5000ms
describe("WHEN: get chats$", () => {
const CHAT_MOCK_1: Chat = {
id: "1",
};
const CHAT_MOCK_2: Chat = {
id: "2",
};
it("THEN: get chats$ should return chat list", (done) => {
service.chats$
.subscribe((data) => {
expect(data.length).toEqual(2);
expect(data[0]).toEqual(CHAT_MOCK_1);
expect(data[1]).toEqual(CHAT_MOCK_2);
done();
})
.unsubscribe();
});
});