rxjs - 如何在 rxjs 中实现服务器轮询
问题描述
我有一个非常简单的服务器轮询方案:
- 调用 API -> 2. onSuccess -> 3. 等待 500ms -> 4. 返回步骤 1
和
- 调用 API -> 2. onError -> 3. 完成
我想使用 rxjs,因为我已经使用了 rxjava。但我似乎无法为我的问题找到合适的解决方案。我试过计时器和间隔,但问题是它们只是无限运行,没有处理程序在等待服务器响应时暂停它们,或者在发生错误时完全退出。尝试使用 retryWhen,但根本无法让它工作。
这就是我要的:
downloadData() {
console.log('downloading data')
$.getJSON('http://localhost:80')
.done((data) => {
console.log('done' + JSON.stringify(data))
setTimeout(() => { this.downloadData() }, 500)
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(`Error: ${textStatus}`)
})
}
如何在 rxjs 中实现相同的功能?
解决方案
你应该看看repeat
运营商:
fromFetch.fromFetch(`https://www.googleapis.com/books/v1/volumes?q=purple cow&maxResults=3`).pipe(
exhaustMap(response => {
if (response.ok) {
// OK return data
return response.json()
} else {
// Server is returning a status requiring the client to try something else.
return of({ error: true, message: `Error ${response.status}` })
}
}),
catchError(err => {
// Network or other error, handle appropriately
return of({ error: true, message: err.message })
}),
filter(resp => !resp.error)
delay(500),
repeat(),
).subscribe()
推荐阅读
- python - 如何设置可检查的菜单设置,真或假?如果是真的做某事
- itext - 使用 itextsharp 识别眼睛看不见但可以使用 Acrobat 搜索的文本
- apache-spark - 将 Parquet 文件加载到 HDFS 表中-Pyspark
- c# - 如何使用 C# Steeltoe 库连接到现有的 ZUUL 服务器?
- azure - 有没有办法根据带有 Runbook/自动化脚本的标签删除资源组?
- webpack - 未找到块列表 Webpack 插件
- flow-project - How is FLOW currently dealing with clipping actions, squash_to_range, no_final_linear
- html - 无法更改 Angular 材质输入占位符的文本颜色
- python - Python:如果元素是另一个嵌套列表中的元素,则删除嵌套列表中的重复元素
- excel - 代码在正常运行时不做任何事情,但在调试模式下会做,一步一步