Andrew
Andrew

Reputation: 2173

RxJS Observable - subscribe once every time a condition met

Observables are new to me, so I'm not even sure it's possible (but I would guess it is). What I would like to achieve is having an observable (Angular 2 http.get call), and subscribe to it once whenever a variable is changed. An example flow would be something like this:

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

The bigger concept is that I would have a UserService and in the constructor I would subscribe to /api/user/me once, whenever there is a token change in the localStorage. Is this a valid use case, and if so, how can I do it with observables?

Upvotes: 2

Views: 2522

Answers (1)

Nypan
Nypan

Reputation: 7246

Something like this should do the trick:

// 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

So basically pass something to localStorageChangedObservable.onNext(...) when you want to trigger an api call.

Upvotes: 1

Related Questions