简体   繁体   中英

RxJS wait until promise resolved

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

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM