RxJS Observable - 每次条件满足时订阅一次

时间:2016-05-27 12:55:25

标签: rxjs observable

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并且在构造函数中,只要localStorage中有令牌更改,我就会订阅/api/user/me一次。这是一个有效的用例,如果是这样,我怎么能用observables来做呢?

1 个答案:

答案 0 :(得分: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(...)