Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJs: Incrementally push stream of data to BehaviorSubject<[]>

Tags:

angular

rxjs5

Basically I'm trying to inflate BehaviorSubject<[]> with array of data which will be loaded in chunks.

BehaviorSubject<[]> will be added with new chunk of data (like Array.push) but I don't want to use another array to store and add to BehaviorSubject.next because this will cause rendering to take too long as the data grow over time.

Any suggestion?

like image 699
Reddy Avatar asked May 30 '17 21:05

Reddy


2 Answers

You can use getValue() method to achieve what you want to do.

Example:

data = new BehaviorSubject<any[]>([]);

addData(foo:any):void{
  // I'm using concat here to avoid using an intermediate array (push doesn't return the result array, concat does).
  this.data.next(this.data.getValue().concat([foo]));
}
like image 68
Supamiu Avatar answered Oct 26 '22 23:10

Supamiu


Instead of using concat, you can instead use the spread operator:

data = new BehaviorSubject<any[]>([]);

addData(foo: any): void {
  this.data.next([...this.data.getValue(), ...foo])
}

I've found this to be a bit more readable than a straight concat

like image 43
TheHanna Avatar answered Oct 26 '22 21:10

TheHanna