RxJS wait until promise resolved

一曲冷凌霜 提交于 2019-12-30 10:35:13

问题


I'm still figuring out reactive programming so I'm pretty sure this is very basic, but the number of stream transformations is pretty overwhelming to a beginner.

I'm creating an Observable from a DOM event. This event should in turn trigger a REST call and all other DOM events will be ignored until this event has been resolved.

const stream = Observable.fromEvent(document, 'some-event')
stream
  .flatMap(() => httpRestService())
  .subscribe(() => {
  })

How do I ignore the events from the stream until the last HTTP promise has resolved?

DOM event
A - - - - B - - - - C
HTTP event
D ...........done - C

回答1:


You could try flatMapFirst which seems to do what you want. The following code could work (jsfiddle here - click anywhere) :

const stream = Observable.fromEvent(document, 'some-event')
stream
  .flatMapFirst(() => httpRestService())
  .subscribe(() => {
  })

Quoting the documentation :

The flatMapFirst operator is similar to the flatMap and concatMap methods described above, however, rather than emitting all of the items emitted by all of the Observables that the operator generates by transforming items from the source Observable, flatMapFirst instead propagates the first Observable exclusively until it completes before it begins subscribes to the next Observable. Observables that come before the current Observable completes will be dropped and will not propagate.

UPDATE

Looking at the source code (https://github.com/Reactive-Extensions/RxJS/blob/master/src/core/linq/observable/switchfirst.js) it seems that while the the current observable has not completed, all the incoming observables in the meantime will be discarded, i.e. not subscribed to.

So if subscribing to these observables triggers the http call (would be interesting to see the code for httpRestService), then there is no unnecessary http call. If those calls are triggered immediately by calling the function and the result is passed through an observable, then there is a possibility that those calls are indeed triggered unnecessarily. In which case, that issue is easily solvable with using the defer operator to do the http call only at subscription time. In short, you need lazy execution of the rest request if you don't already have it.



来源:https://stackoverflow.com/questions/37173877/rxjs-wait-until-promise-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!