I am interested in implementing this functionality using rxjs:
- I need to make a series of http calls;
- I want these calls to be executed sequentially;
- I want to transform the result of each call into an Observable stream of InfoMessage;
Pseudo-code that is not working as intended:
class InfoMessage {
constructor(public message: string) {}
}
doAllRequests() : Observable<InfoMessage> {
return Observable.create((obs: Observer<InfoMessage>) => {
doRequest("http://test1.com").map((res: RxRequestResponse) => obs.next(new InfoMessage("request1 done")));
doRequest("http://test2.com").map((res: RxRequestResponse) => obs.next(new InfoMessage("request2")));
doRequest("http://test3.com").map((res: RxRequestResponse) => obs.next(new InfoMessage("request3")));
obs.complete();
});
}
doRequest(url: string) : Observable<RxRequestResponse> {
// utilizing an http client wrapped in an Observable of type RxRequestResponse
}
doAllRequests().subscribe(next => console("Message: " + next.message));
Update: recommended approach by Martin: Your solution appears to work, but only if I subscribe to the initial request like this:
Observable.create((observer: Observer<InfoMessage>) => {
doRequest("http://test1.com")
.do(response => observer.next(new InfoMessage("request1 done")))
.concatMap(() => doRequest("http://test2.com"))
.do(response => observer.next(new InfoMessage("request2")))
.concatMap(() => doRequest("http://test3.com"))
.do(response => {
observer.next(new InfoMessage("request3"));
observer.complete();
}).subscribe();
})
I prefer to delay subscription and delegate it to the caller of doAllRequests(). Any suggestions?
Update: proposed solution by Quentin
This method functions well and is more efficient for executing large scripts with multiple requests, concerning code verbosity.
As this is now the method I am using, I am changing my accepted answer. However, Martin, I appreciate your input! Are we good?