I have a very simple server polling scenario:
- call API -> 2. onSuccess -> 3. wait 500ms -> 4. go back to step 1
and
- call API -> 2. onError -> 3. finish
I want to be using rxjs as I already use rxjava. But I just can't seem to arrive on a proper solution for my problem. I've tried timer and interval, but the problem is that they just run infinitely with no handlers to pause them while waiting for server to response or quit altogether when error occurs. Tried using retryWhen, but was not able to get it work at all.
This is what I want:
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}`)
})
}
How to achieve the same thing in rxjs?
You should take a look at the repeat
operator:
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()