Reputation: 927
The problem i have a list of id's that i can load cheaply, loading details for each is more expensive.
So i want to load the entire list of 'id objects', subscribe to the stream fetch the first 5 and on a mouse click fetch the next 5(paging back and forth).
The resulting stream i will then make an xhr request for each item in the current batch.
var clicks = Rx.Observable.fromEvent($nextPageButton, 'click')
var arrayObs = Observable.from([{id:3}, {id:2}, {id:1}, {id:6}, {id:5}, {id:4}]);
I have tried countless ways of mapping merging etc. Cant get the hang of it.
simple plunker
https://plnkr.co/edit/W83d3xftZv25YqhOF8uL?p=preview
Upvotes: 0
Views: 36
Reputation: 5036
If you want to only use observables, you can do as follow
let page = 0;
let size = 3;
let arrayObs = Observable.from([{id:3}, {id:2}, {id:1}, {id:6}, {id:5}, {id:4}]);
// Click observables that emit the page we want to display.
let clickPreviousObs = Observable.fromEvent(this.prevButton.nativeElement, 'click').map(() => {
page--;
return page;
});
let clickNextObs = Observable.fromEvent(this.nextButton.nativeElement, 'click').map(() => {
page++;
return page;
});
// Merge click observables so there is only one observable that emit the page, and start with the first page.
let pageObs = Observable.merge(clickPreviousObs, clickNextObs).startWith(page);
// When I get a new page, get the corresponding ids.
let resultObs = pageObs.flatMap((currentPage) => {
console.log('Page ', currentPage);
return arrayObs.skip(currentPage * size).take(size);
});
resultObs.subscribe((res) => {
console.log('Result', res);
});
See plunkr
Upvotes: 1