Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 => {

           //some instructions

        },
        error => alert(error),
        () => console.log("finished"));
}
k.unsubscribe();
like image 810
user2243952 Avatar asked Oct 24 '25 19:10

user2243952


2 Answers

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 */);
like image 138
Kroltan Avatar answered Oct 27 '25 09:10

Kroltan


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 ms
const k$ = this.firebase(user)
    .takeUntil(timer$) // subscribe to k$ until the timer$ finishes
    .subscribe( ... )
like image 31
vma_93 Avatar answered Oct 27 '25 10:10

vma_93



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!