RxJS等到承诺解决 [英] RxJS wait until promise resolved

查看:101
本文介绍了RxJS等到承诺解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在研究反应式编程,因此我敢肯定这是非常基础的,但是对于初学者来说,流转换的数量是非常庞大的.

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.

我正在根据DOM事件创建一个Observable.反过来,此事件将触发REST调用,并且所有其他DOM事件都将被忽略,直到该事件解决为止.

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(() => {
  })

在最后一个HTTP承诺解决之前,我如何忽略流中的事件?

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

推荐答案

您可以尝试 jsfiddle在这里-单击任意位置):

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(() => {
  })

引用文档:

flatMapFirst运算符与上述的flatMap和concatMap方法类似,但是,它不会发出该运算符通过转换源Observable中的项目而生成的所有Observable发出的所有项目,而是传播第一个Observable的flatMapFirst.直到它完成,才开始订阅下一个Observable.当前可观察对象完成之前的可观察对象将被删除并且不会传播.

更新

查看源代码(https://github.com/Reactive-Extensions/RxJS/blob/master/src/core/linq/observable/switchfirst.js )似乎当前的可观察对象尚未完成,但所有传入的可观察对象同时将被丢弃,即未订阅.

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.

因此,如果订阅这些可观察变量会触发http调用(查看 httpRestService 的代码会很有趣),那么就不会有不必要的http调用.如果通过调用该函数立即触发了这些调用,并且结果通过可观察对象传递,则可能确实确实不必要地触发了这些调用.在这种情况下,使用 defer 运算符仅在订阅时进行http调用,可以轻松解决该问题.简而言之,如果还没有剩余的请求,则需要延迟执行.

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.

这篇关于RxJS等到承诺解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆