最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to cancel RXJS subscribe after a while - Stack Overflow

programmeradmin0浏览0评论

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

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();
Share Improve this question edited Jul 9, 2017 at 22:40 Kroltan 5,1565 gold badges38 silver badges64 bronze badges asked Jul 9, 2017 at 21:11 user2243952user2243952 2773 gold badges6 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

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

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( ... )
发布评论

评论列表(0)

  1. 暂无评论