首页 > 解决方案 > 如何在 rxjs 中实现服务器轮询

问题描述

我有一个非常简单的服务器轮询方案:

  1. 调用 API -> 2. onSuccess -> 3. 等待 500ms -> 4. 返回步骤 1

  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 中实现相同的功能?

标签: rxjsreactive-programmingreactive-extensions-js

解决方案


你应该看看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()

推荐阅读