user2243952
user2243952

Reputation: 277

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();

Upvotes: 4

Views: 6466

Answers (2)

Kroltan
Kroltan

Reputation: 5156

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 */);

Upvotes: 10

vma_93
vma_93

Reputation: 194

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( ... )

Upvotes: 6

Related Questions