Skip to content Skip to sidebar Skip to footer

How To Cancel Rxjs Subscribe After A While

If the user's internet is slow and the subscription is taking too long(more than 30 sec), I want to cancel it. const k = this.firebase(user) .subscribe(data => {

Solution 1:

Check out the Operators documentation and you will find many interesting things.

Simply use the Timeout operator, which is made for specifically this case:

const k = this.firebase(user)
    .timeout(30 * 1000)
    .subscribe(
        data => { /* do stuff*/ },
        error => { /* handle it */ },
        () => { /* finished */ }
    );

The timeout will wait for a value to be emitted up to the time limit, at which point it will end the observable with a failure.

This means that the error handler will be called if nothing was received within 30 seconds, and you can use that to notify the user, if you want.

Update: Apparently the Firebase client keeps the observable running after receiving a value (presumably so you get notified of further updates). And since the Observable is never completed, Timeout will act after 30 (or whatever you pass as duration) seconds after receiving the data, causing the stream to fail.

To convert the "streaming" Observable into a single-event Observable, use the Take operator before timing out:

this.firebase(user)
    .take(1)
    .timeout(wait)
    .subscribe(/* etc */);

Solution 2:

You can create another Observable stream using the timer operator and listen to stream k until the timer stream has finished.

ex:

const timer$ = Observable.timer(30000) // time in msconst k$ = this.firebase(user)
    .takeUntil(timer$) // subscribe to k$ until the timer$ finishes
    .subscribe( ... )

Post a Comment for "How To Cancel Rxjs Subscribe After A While"