This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Use groupBy in real RxJS applications

5:21 RxJS lesson by

This lesson will show when to apply groupBy in the real world. This RxJS operator is best suited when a source observable represents many data sources, e.g. an observable for multitouch events.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

This lesson will show when to apply groupBy in the real world. This RxJS operator is best suited when a source observable represents many data sources, e.g. an observable for multitouch events.

Avatar
Naresh

Hi André Staltz,

Thank you for this amazing work. Its was easy to understand these concepts but i have one question. I am trying to figure out an answer for this. perhaps you can help

in this example groupBy operator groups based on keys code. output observable is merged based on the emission rate delay and merged.

How it is possible to wait for the complete event from source and then use the grouped observables one by one instead of merging them in the arriving order.

const all = busObservable
  .groupBy(obj => obj.code)
  .count()
  .mergeMap(obj =>obj.skip(1))
  .filter( obs => obs.code == 'en-us')

I can only print english or based on language i specify in filter.

current output :

hello amazing olá hola mundo world mundo asombroso maravilhoso

expected output :

how it is possible to get like this.

// ...en-us-...pt-br -...es 
hello amazing world olá mundo maravilhoso hola mundo asombroso
In reply to egghead.io
Avatar
Naresh

I found it. reduce will do after completion.

const all = busObservable
  .groupBy(obj => obj.code)
  .mergeMap(lGroup => lGroup.skip(1)
                    .reduce((a, c) => {
                      return [...a,c.value]
                    }, []))
  .reduce( (acc,current) => {
    return [...acc,...current]
  },[])
In reply to Naresh
Avatar
Andre

Hi Naresh. That's right, reduce works. In general, reduce is scan() plus last(). It is also possible to use one of the buffer operator variants, then last().

In reply to Naresh
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?