10

I have list, that should simulate the stream :

list = [
  {name : 'Str1', age: 10},
  {name : 'Str2', age: 10},
  {name : 'Str3', age: 10}
];

and I've created an Observable from this list:

Observable.from(this.list).skip(this.currentPage * this.pageSize).take(this.pageSize).subscribe(data => this.pagerList = data, console.error);

And in the subscribe method I get the values one by one. How I'm supposed to wait for the whole data to be returned and then to get the whole list. There is take() operator, and after it the Observable have to stop.

I don't want to put every value one by one in the array.

I'm new here, not only for angular, but for javascript as well.

3 Answers 3

10

Have you tried to use toArray operator?.

let list = [
  { name: 'Str1', age: 10 },
  { name: 'Str2', age: 10 },
  { name: 'Str3', age: 10 },
  { name: 'Str4', age: 10 },
  { name: 'Str5', age: 10 },
  { name: 'Str6', age: 10 }
];

let currentPage = 2;
let pageSize = 2;

Rx.Observable.from(list)
  .skip(currentPage * pageSize)
  .take(pageSize)
  .toArray()
  .subscribe(data => console.log(data), console.error);
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

4

The scan operator should do what you want

Observable.from(this.list)
.skip(this.currentPage * this.pageSize)
.take(this.pageSize)
.scan([], acc, curr) => {acc.push(curr); return acc;});
.subscribe(data => this.pagerList = data, console.error);

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan

2 Comments

rxmarbles.com/#scan this is like reduce but after the result is received. Thank you for the answer.
With scanyou get an updated array after each event and with toArray you only get one array at the end when the observable completes.
1

I think this is more appropriate solution:

Observable.of(this.list).map(x => x.slice(this.currentPage * this.pageSize)).map(x => x.slice(0, this.pageSize)).subscribe(data => this.pagerList = data, console.error);

2 Comments

I don't understand this one. In the first map function you get object. How can you slice object?
Observable.of(this.list) creates sequence of one element which type is array, map is applied to observable value, in this case it is array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.