Custom disposal

When the create factory operator is used, it is possible to provide a custom disposal function. This function will be called when the dispose method of the disposable object returned by the subscription is called. Consider the following example, similar to the previous one, but with the observable being a custom one:

def on_subscribe(observer):
def dispose():
print("disposing custom observable")

observer.on_next(1)
observer.on_next(2)
observer.on_next(3)
observer.on_completed()
return dispose

numbers = Observable.create(on_subscribe)
subscription = 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")
)
subscription.dispose()

Here, the subscribe function returns a disposal function. Running the preceding example provides the following result:

on_next 1
on_next 2
on_next 3
on_completed
disposing custom observable

The dispose function of the custom observable was called when the subscription was disposed. This allows us to free resources allocated on the subscription. A typical use case is to unsubscribe from another observable.

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

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