Subscribing to an observable

When an observer subscribes to an observable, it listens to the observable with three handlers, as follows:

  • on_next, which is called each time an item is emitted on the observable
  • on_error, which is called when the observable completes on error
  • on_completed, which is called when the observable completes on success

Handling each of these three kinds of events is optional. However, the on_error handler should always be implemented to avoid losing errors silently, which can make a whole program stop working. There are two ways to implement these handlers. The first way is by subclassing the Observer class and implementing the three handlers, as follows:

class MyObserver(Observer):
def on_next(self, item):
print("on_next {}".format(item))

def on_completed(self):
print("on_completed")

def on_error(self, error):
print("on_error: {}".format(error))

numbers = Observable.from_([1, 2, 3])
numbers.subscribe(MyObserver())

It is also possible to register callbacks with keyword arguments. The following is the same example, but with lambdas as handlers:

numbers = Observable.from_([1, 2, 3])
numbers.subscribe(
on_next = lambda i: print("on_next {}".format(i)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)
..................Content has been hidden....................

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