The materialize/dematerialize operators

The materialize and dematerialize operators allow us to serialize/deserialize an observable's events. The on_next, on_completed, and on_error events can be converted to items and back. The following figure shows the marble diagram of the materialize operator:

Figure 9.19: The materialize operator

The following figure shows the marble diagram of the dematerialize operator:

Figure 9.20: The dematerialize operator

The prototype of the materialize operator is the following:

Observable.materialize(self)

The prototype of the dematerialize operator is the following:

Observable.dematerialize(self)

Here is an example of the materialize operator:

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

numbers.materialize().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")
)

This example gives the following result:

on_next OnNext(1)
on_next OnNext(2)
on_next OnNext(3)
on_next OnNext(4)
on_next OnCompleted()
on_completed

The four numbers are received wrapped in OnNext objects. Then, an OnCompleted item is received before the observable completes. So, all events of the observable have been received as items. These wrapped items are defined in the rx.core.notification module. They can then be used by the dematerialize operator this way:

from rx.core.notification import OnNext, OnCompleted

numbers = Observable.from_([OnNext(1), OnNext(2), OnNext(3), OnNext(4), OnCompleted()])

numbers.dematerialize().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")
)

This gives the following result:

on_next 1
on_next 2
on_next 3
on_next 4
on_completed

The four numbers are received as items, and the OnCompleted item is transformed to a completion event.

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

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