The from_future operator

The from_future operator converts a future object to an observable that emits zero, or one item. The marble diagram of this operator is shown in the following figure:

Figure 4.18: The from_future operator

Its prototype is as follows:

Observable.from_future(future)

This operator converts future to an observable that emits the result of future if it succeeds, or the error raised by future if it does not. The following is an example of its usage:

import asyncio
from rx import Observable


async def foo(future):
await asyncio.sleep(1)
future.set_result(2)


loop = asyncio.get_event_loop()
done = loop.create_future()
asyncio.ensure_future(foo(done))

number = Observable.from_future(done)
print("subscribing...")
number.subscribe(
lambda i: print("on_next: {}".format(i)),
lambda e: print("on_error: {}".format(e)),
lambda: print("on_completed")
)

print("starting mainloop")
loop.run_until_complete(done)
loop.close()

The done future is converted to an observable. This done future is completed when the foo coroutine completes, after a second of delay. The following is the result of this code:

subscribing...
starting mainloop
on_next: 2
on_completed

The on_next trace is printed a second after the mainloop has started.

There is a complementary operator to from_future and to_future. The to_future operator converts an observable to a future.

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

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