Just starting out with RxJS
version 6.5.5
, I'm encountering an issue with the groupBy
operator. Here's a simplified example to showcase the problem.
I have a function called retrieveFiles()
that retrieves an array of strings.
function async retrieveFiles(): Promise<string[]> {
return ['file1.txt', 'file2.txt', 'file3.txt', 'directory1', 'directory2'];
}
In real-life scenario, this function would fetch data from a remote source.
Assuming I want to group the filenames based on the first 4 characters.
With RxJS
, I can achieve this using the following code snippet.
of(retrieveFiles()).pipe(
concatMap(v => v),
mergeMap(value => value),
groupBy(
(name: string) => name.substr(0, 4),
(name: string) => name,
),
mergeMap(group$ => group$.pipe(toArray())),
)
.subscribe(console.log);
This will output two sets of values to the subscriber.
[ 'file1.txt', 'file2.txt', 'file3.txt' ]
[ 'directory1', 'directory2' ]
Now let's add in the timer
and make some changes to the code. Essentially, we are now creating a polling mechanism.
timer(0, 1000)
.pipe(
concatMap(() => this.retrieveFiles()),
mergeMap(value => value),
groupBy(
(name: string) => name.substr(0, 4),
(name: string) => name,
),
mergeMap(group$ => group$.pipe(toArray())),
)
.subscribe(console.log);
Surprisingly, this doesn't produce any output. What could be the difference between these two implementations?