Reputation: 2715
Here it says :
// RxJS v6+
import { from } from 'rxjs';
import { groupBy, mergeMap, toArray } from 'rxjs/operators';
const people = [
{ name: 'Sue', age: 25 },
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 25 },
{ name: 'Sarah', age: 35 }
];
//emit each person
const source = from(people);
//group by age
const example = source.pipe(
groupBy(person => person.age),
// return each item in group as array
mergeMap(group => group.pipe(toArray()))
);
/*
output:
[{age: 25, name: "Sue"},{age: 25, name: "Frank"}]
[{age: 30, name: "Joe"}]
[{age: 35, name: "Sarah"}]
*/
const subscribe = example.subscribe(val => console.log(val));
In my code I don't create an observable with the 'from' operator, but rather with BehaviorSubject.asObservable() method.
Person { name: string, age: number }
private _all: BehaviorSubject<Person[]>;
all: Observable<Person[]>;
constructor() {
this._all = new BehaviorSubject<Person[]>([]);
this.all = this._all.asObservable();
}
I can iterate over 'all' with the async pipe. But when I try to use the groupBy operator I get the array itself, instead of the containing persons one by one as a stream :
this.all.pipe(
groupBy(
item => ... <-- here 'item' is Person[], not a Person
)
);
What am I doing wrong ?
Upvotes: 1
Views: 521
Reputation:
The simple answer is (unfortunately) that it is not possible this way. Here is another post concerning a similar question.
You could do a step in between to reach the wanted goal:
Option 1: without subscription
// directly access the BehaviorSubject's value
const list = from(this._all.value);
this.list.pipe(
groupBy(
item => ...
)
);
Option 2: with subscription, as it is an Observable
// catch the plain list inside the subscription
this.all.subscribe(result => {
const list = from(result);
this.list.pipe(
groupBy(
item => ...
)
);
});
Upvotes: 2