How To Convert A Sequence Of Promises Into Rx.observable With Rxjs?
I'm trying to create an Rx.Observable from a chain of Promises with RxJS. The difference from this question is that I have unknown number of Promises, and every Promise depends on
Solution 1:
You can wrap the async function
in something that voids its results:
functiontoVoid<A>(fn: A => Any): A =>Void {
return x => voidfn(x)
}
(forgive my lacking knowledge of TypeScript, but I hope you can guess what it's supposed to do)
With that, you should be able to call
let observable = Rx.Observable.create<T>(toVoid(async obs => {
…
}));
But maybe you shouldn't do that. Don't throw away the promise, use it instead to attach the appropriate error handler:
let observable = Rx.Observable.create<T>(obs => {
(async () => {
…
}()).catch(err => {
obs.onError(err);
});
});
Solution 2:
The problem was solved using .then() + recursion, without async/await:
private getPages<T>(initialPromise: PromiseLike<IODataCollectionResult<T>>): Rx.Observable<T> {
returnRx.Observable.create<T>(obs => {
const getPage = (promise: PromiseLike<IODataCollectionResult<T>>) => {
promise.then(page => {
page.value.forEach(v => obs.onNext(v));
if (page['@odata.nextLink']) {
let nextPageUrl =<string>page['@odata.nextLink'];
let nextPagePromise =<PromiseLike<IODataCollectionResult<T>>>this.resource(nextPageUrl).get().$promise;
getPage(nextPagePromise);
}
else {
obs.onCompleted();
}
});
}
getPage(initialPromise);
});
}
Post a Comment for "How To Convert A Sequence Of Promises Into Rx.observable With Rxjs?"