如果用户的网速很慢并且订阅时间太长(超过30秒),我想取消它。
const k = this.firebase(user)
.subscribe(data => {
//some instructions
},
error => alert(error),
() => console.log("finished"));
}
k.unsubscribe();
查看运营商 http://reactivex.io/documentation/operators.html文档,你会发现很多有趣的东西。
只需使用Timeout http://reactivex.io/documentation/operators/timeout.html运算符,专门针对这种情况而设计:
const k = this.firebase(user)
.timeout(30 * 1000)
.subscribe(
data => { /* do stuff*/ },
error => { /* handle it */ },
() => { /* finished */ }
);
The timeout
将等待一个值在时间限制内发出,此时它将以失败结束可观察值。
这意味着error
如果 30 秒内没有收到任何消息,则会调用处理程序,如果需要,您可以使用它来通知用户。
Update:显然,Firebase 客户端在收到值后会保持 observable 运行(大概是为了让您收到进一步更新的通知)。由于 Observable 永远不会完成,Timeout 将在收到数据后 30 秒(或您传递的持续时间)后起作用,导致流失败。
要将“流式”Observable 转换为单事件 Observable,请使用Take http://reactivex.io/documentation/operators.html超时前的运算符:
this.firebase(user)
.take(1)
.timeout(wait)
.subscribe(/* etc */);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)