mmjmanders
mmjmanders

Reputation: 1553

RxJS groupBy not getting values on subscribe

I have a very long list in a MongoDB instance consisting of StockPrices with the following properties:

I want to group them by symbol. I use an observable to get the list of StockPrices and inject them in the component, which is this:

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {StockPrice} from '../../model';
import {flatMap, groupBy, mergeMap, toArray} from 'rxjs/operators';
import {of, zip} from 'rxjs';

@Component({
    selector: 'compare-chart',
    templateUrl: './compare-chart.component.html',
    styleUrls: ['./compare-chart.component.scss']
})
export class CompareChartComponent implements OnInit {

    constructor(private route: ActivatedRoute) {
    }

    ngOnInit() {
        this.route.data.pipe(
            flatMap((data: { stockPrices: StockPrice[] }) => data.stockPrices),
            groupBy(stockPrice => stockPrice.symbol),
            mergeMap(group => zip(of(group.key), group.pipe(toArray())))
        ).subscribe(console.log);
    }

}

For some reason there is no value emitted and shown in the console, however I do see that the list of StockPrices is retrieved from the server. I tried all hints from rxjs.dev and learnrxjs.io.

Any ideas?

Upvotes: 0

Views: 361

Answers (1)

bryan60
bryan60

Reputation: 29355

flatMap expects an observable to be returned, it seems what you want is to do this instead:

flatMap((data: { stockPrices: StockPrice[] }) => from(data.stockPrices)),

from will turn an array into an observable stream that flatMap can operate on so groupBy can do it's thing.

Worth noting, this isn't strictly necesarry, you can just use the map operator and a synchronous groupBy tool from like lodash or soemthing.

groupBy is a kind of complex operator and it's really only needed if you want to group an actual stream, like if you had a live stream of stock prices coming in from a web socket or a poller or something.

Upvotes: 1

Related Questions