Synchronous stream of responses from a stream of requests with RxJS

爱⌒轻易说出口 提交于 2019-12-05 10:33:52

Try replacing flatMap with concatMap in your first code sample and let me know if the resulting behaviour corresponds to what you are looking for.

responseStream = requestStream.concatMap(//I replaced `flatMap`
  sendRequest,
  (val, response)=>{ return {val, response}; }
);

Basically concatMap has a similar signature than flatMap, the difference in behaviour being that it will wait for the current observable being flattened to complete before proceeding with the next one. So here:

  • a requestStream value will be pushed to the concatMap operator.
  • the concatMap operator will generate a sendRequest observable, and whatever values out of that observable (seems to be a tuple (val, response)) will be passed through the selector function and the object result of that will be passed downstream
  • when that sendRequest completes, another requestStream value is processed.
  • In short, your requests will be processed one by one

Alternatively, maybe you want to use defer to defer the execution of the sendRequest.

responseStream = requestStream.concatMap(//I replaced `flatMap`
  function(x){return Rx.Observable.defer(function(){return sendRequest(x);})},
  (val, response)=>{ return {val, response}; }
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!