问题
I keep reading rxjs documentation but getting lost in all the operators..
this is what i got so far
let obs = Observable.from([1, 3, 5])
so what i need this to do is take()
some set amount from the array. use the results in a post request, when that comes out successful then i need to restart the process. I want to collect all the results, and keep progress as the process is going (for a progress bar)
I don't need the code for all of that. what i really need to know is how to use rxjs to split this array up.. send part of it, and restart the process until theres nothing left to send.
FINAL SOLUTION
var _this = this
function productsRequest(arr) {
return _this.chainableRequest('post', `reports/${clientId}/${retailerId}/`, loadedProductsReport, {
'identifiers': arr,
'realTime': true
})
}
let arrayCount = Math.ceil(identifiers.length/10)
let obs = Observable.from(identifiers)
.bufferCount(10)
.concatMap(arr => {
arrayCount--
return arrayCount > 0 ? productsRequest(arr) : Observable.empty()
})
let subscriber = obs.subscribe(
value => console.log(value)
)
chainable request method in parent
chainableRequest(method: string, endpoint: string, action: Function, data = {}, callback?: Function){
let body = (<any>Object).assign({}, {
headers: this.headers
}, data)
return this._http[method.toLowerCase()](`${this.baseUri}/${endpoint}`, body, body)
.map((res: Response) => res.json())
}
回答1:
This largely depends on what you're trying to achieve.
If you want to recursively call an Observable based on some previous Observable and you don't know how many times you're going to call it then use expand() operator.
For example this demo recursively creates 5 requests based on the response from the previous call (count
property):
import { Observable } from 'rxjs/Observable';
function mockPostRequest(count) {
return Observable.of(`{"count":${count},"data":"response"}`)
.map(val => JSON.parse(val));
}
Observable.of({count: 0})
.expand(response => {
console.log('Response:', response.count);
return response.count < 5 ? mockPostRequest(response.count + 1) : Observable.empty();
})
.subscribe(undefined, undefined, val => console.log('Completed'));
Prints to console:
Response: 0
Response: 1
Response: 2
Response: 3
Response: 4
Response: 5
Completed
See live demo: http://plnkr.co/edit/lKNdR8oeOuB2mrnR3ahQ?p=preview
Or if you just want to call a bunch of HTTP request in order one after another (concatMap() operator) or call all of them at once and consume them as they arrive (mergeMap() operator):
Observable.from([
'https://httpbin.org/get?1',
'https://httpbin.org/get?2',
'https://httpbin.org/get?3',
])
.concatMap(url => Observable.of(url))
.subscribe(response => console.log(response));
Prints to console:
https://httpbin.org/get?1
https://httpbin.org/get?2
https://httpbin.org/get?3
See live demo: http://plnkr.co/edit/JwZ3rtkiSNB1cwX5gCA5?p=preview
来源:https://stackoverflow.com/questions/40295717/angular-2-rxjs-need-some-help-batching-requests