如何在rxjs中实现服务器轮询

时间:2019-12-26 16:47:51

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

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

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

  
      
  1. 调用API-> 2. onError-> 3.完成
  2.   

我想使用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中实现相同的目的?

1 个答案:

答案 0 :(得分: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()
相关问题