一段时间后如何取消RXJS订阅 [英] how to cancel RXJS subscribe after a while

查看:198
本文介绍了一段时间后如何取消RXJS订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户的互联网速度慢且订阅时间过长(超过30秒),我想取消订阅.

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

推荐答案

查看操作员文档,您会发现很多有趣的东西.

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

timeout将等待一个值被发射到时间限制,此时它将以可观察的结果结束.

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.

这意味着error处理程序将在30秒内未接收到任何内容时被调用,并且您可以根据需要使用该通知程序通知用户.

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.

更新:显然,Firebase客户端在接收到值后保持可观察的运行(大概是这样,您会收到进一步更新的通知).而且由于Observable永远不会完成,因此超时将在收到数据后30秒(或您作为持续时间传递的任何秒数)之后起作用,从而导致流失败.

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

这篇关于一段时间后如何取消RXJS订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆