The using operator

The using operator allows us to associate the lifetime of a resource with the lifetime of an observable. The following figure shows the marble diagram of this operator:

Figure 9.24: The using operator

When called, the using operator creates an observable and a resource object. The observable is created via a factory function. When the observable completes, then the resource object is automatically disposed of.

Its prototype is the following:

Observable.using(cls, resource_factory, observable_factory)

This operator is a factory operator; it creates an observable via the observable_factory parameter. resource_factory is a function that will be called to create the resource object. This function must return a disposable object so that the resource can be disposed of when the observable completes.

Here is an example of the using operator:

from rx.disposables import AnonymousDisposable

def resource():
print("create resource at {}".format(datetime.datetime.now()))
def dispose():
print("dispose resource at {}".format(datetime.datetime.now()))

return AnonymousDisposable(dispose)


Observable.using(resource,
lambda r: Observable.just(1).delay(200)).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")
)
time.sleep(500)

The resource function is the resource factory function (even though it does nothing useful here). The nested dispose function allows us to free this resource. It is returned as a disposable object. This resource function is provided as the first parameter of the using operator. The second parameter is lambda, which creates an observable that completes 200 milliseconds after its creation.

This example gives the following result:

create resource at 2018-08-16 00:04:24.491232
on_next 1
on_completed
dispose resource at 2018-08-16 00:04:24.694836

The resource function is called when the using operator is called, the observable completes 200 milliseconds afterward, and the dispose function is called.

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

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