【问题标题】:How to implement server polling in rxjs如何在 rxjs 中实现服务器轮询
【发布时间】:2020-04-16 20:35:19
【问题描述】:

我有一个非常简单的服务器轮询场景:

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

【问题讨论】:

    标签: rxjs reactive-programming reactive-extensions-js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2012-06-10
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 2016-04-28
      • 1970-01-01
      相关资源
      最近更新 更多