【问题标题】:RxJS Observable - subscribe once every time a condition metRxJS Observable - 每次满足条件时订阅一次
【发布时间】:2016-09-25 19:57:25
【问题描述】:

Observables 对我来说是新的,所以我什至不确定它是否可能(但我猜它是可能的)。我想要实现的是拥有一个可观察的(Angular 2 http.get 调用),并在变量更改时订阅它一次。示例流程如下所示:

let x = false;
// ... somewhere later I change "x" to true
subscribe gets called once, x => false
// stuffs happening, 10 minutes later x => true again
subscribe gets called once, x => false

更大的概念是我将拥有一个UserService,并且在构造函数中我将订阅/api/user/me 一次,只要在localStorage 中发生令牌更改。这是一个有效的用例吗?如果是,我该如何使用 observables 来做到这一点?

【问题讨论】:

  • 那么你想要做的是每次本地存储更改时进行一次api调用?只是想得到你想做的事,这样我才能给出体面的答案..
  • 是的,基本上就是这样。每次本地存储项更改并且不为空时进行一次 api 调用。

标签: rxjs observable


【解决方案1】:

这样的事情应该可以解决问题:

// Observable that on subscription will result in an api call. It would 
// naturaly have another type in an acaual use case.
let apiCallObservable : Rx.Observable< { someResult: any }>;

let localStorageChangedObservable = new Rx.Subject<boolean>()

localStorageChangedObservable
    // only care about local storage change if not null
    // This is just an example the type of localStorageChangedObservable
    // could be anything you want, and you could check anything you want in the 
    // "where" 
    .where(v => v != null)
    .selectMany(() =>
        // Take one is to make sure we terminate apiCallObservable after recieving
        // one result from it. 
        apiCallObservable.take(1))
    .subscribe(
        (result: { someResult: any}) => {

            // here we would have the result from the call to apiCallObservable
        });

// To execute the chain abouve we would pass values to the localStorageChangedObservable 
// subject like this:

localStorageChangedObservable.onNext(true); // results in api call and result in subscribe
localStorageChangedObservable.onNext(null); // results in nothing.
localStorageChangedObservable.onNext(false); // results in api call and result in subscribe

所以当你想触发一个 api 调用时,基本上传递一些东西给localStorageChangedObservable.onNext(...)

【讨论】:

  • 有问题,说Property 'where' does not exist on type 'Subject&lt;any&gt;'.我猜是filter
  • 好的,我认为这是与 Angular 2 相关的问题。默认情况下,您需要包含比 Angular 更多的 rxjs(我不是 Angular 专家)。这是 rxjs 存储库github.com/Reactive-Extensions/RxJS,包含所有内容,请使用 dist 文件夹中的 rx.all.js。而且我也意识到我用打字稿而不是javascript写了我的分析器,但我想你还是明白了?
  • 是的,我正在使用打字稿,所以很酷,谢谢!我已经将where 替换为filter,将selectMany 替换为flatMap,看起来它正在工作,但是,对于每次更改它都会发出3 个请求,但我很确定这与角度有关!再次感谢!
  • 上面的代码应该产生一个请求,所以它必须与其他东西相关。确保您没有订阅其他地方可观察到的 api 调用。
  • 如果您使用的是 Angular2,RxJS 存储库实际上是 here
猜你喜欢
  • 1970-01-01
  • 2019-05-10
  • 2020-01-11
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多