Squiggs.
Squiggs.

Reputation: 4474

RxJS detect long running subscription

I'm currently using RxJS Observables / Subscription to perform HTTP requests as code similar to below demonstrates:

this.waiting = true;
this.doSomething().subscribe(
      (result) => {
        this.waiting = false;
        this.showResult= true;
      }
);

What I really want to do, is only set this.waiting to true on a predetermined length of time. In other words, you are only really 'waiting' if the Observable hasn't come back within say 30 seconds. Wondering how to achieve that. I see that there is a .timer method available, but that would only start subscribing after that length of time?

Upvotes: 1

Views: 450

Answers (2)

martin
martin

Reputation: 96889

Have a look at timeout() and timeoutWith() operators. These have no documentation but from their parameters you can guess what they do.

The timeout() operator send an error notification after some time of inactivity.

The timeoutWith() I think let's you replace the source Observable with another Observable after some time of inactivity.

Eventually, if you want to avoid these two operators you can use Observable.race that subscribes internally only to the first Observable that emits:

Observable.race(Observable.timer(30 * 1000).take(1), this.doSomething())

Upvotes: 3

kit
kit

Reputation: 4920

I don't know an operator that does this but this js code should do

const source = Rx.Observable.of(1).delay(1000);
const sub = source.subscribe(val => console.log(val));
setTimeout(() => {
    sub.unsubscribe();
    console.log('timeout')
}, 500);

you can play around with delay and setTimeout values.

Upvotes: 0

Related Questions