The retry operator

The retry operator repeats the sequence of the source observable for a number of times when an error is raised. Its marble diagram is shown in the following figure:

Figure 4.16: The retry operator

Its prototype is as follows:

Observable.retry(self, retry_count=None):

The retry_count argument indicates how many times the operator will subscribe to the observable. So, the number of retry attempts is retry_count, minus 1. The following is an example of how to use it:

subscribe_count = 0
def on_subscribe(observer):
global subscribe_count
subscribe_count += 1
if subscribe_count == 1:
observer.on_next(1)
observer.on_error("error!")
else:
observer.on_next(1)
observer.on_next(2)
observer.on_next(3)
observer.on_completed()


err = Observable.create(on_subscribe)
err.retry(2)
.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

The preceding code provides the following results:

item: 1
item: 1
item: 2
item: 3
completed

A first, the subscription emits the item 1 and then raises an error. The retry operator attempts a second subscription, which succeeds. So the numbers 1, 2, and 3 are emitted before the observable completes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.155