官术网_书友最值得收藏!

The from_callback operator

The from_callback operator is a higher order function. It returns a function that returns an observable. This observable emits a single item: the result of a callback function provided as a parameter of the operator. This callback function is called when the observable is being subscribed. The marble diagram of this operator is shown in the following figure:

Figure 4.10: The from_callback operator

Its prototype is as follows:

Observable.from_callback(func, selector=None)

The return value of the from_callback operator is a function. This function returns an observable, and must be called with the parameters to pass when func is called later on. The func callback is called when the of observable is being subscribed.

An optional selector parameter can be provided. This is a function called with the result of func as input parameters. When the selector parameter is provided, the item emitted on the observable is the return value of the selector parameter.

This operator does not accept a scheduler parameter. The whole call flow is always synchronous.

The following code is an example of its usage:

def foo(what, handler):
print("foo: {}".format(what))
handler("hello " + what)

callback = Observable.from_callback(foo)
cbk_obs = callback("world")
print("subscribing...")
cbk_obs.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

When from_callback is called, a function is returned and stored in the callback variable. This callback operator is then invoked with the world parameter. The result of this call is an observable whose single item is the result of foo being called with the world parameter. Upon subscription, foo is called and a hello world item is received:

subscribing...
foo: world
item: hello world
completed

主站蜘蛛池模板: 三穗县| 卢氏县| 广宁县| 巴彦淖尔市| 永平县| 类乌齐县| 秦皇岛市| 饶河县| 望江县| 绥芬河市| 灵石县| 万全县| 天镇县| 阿拉尔市| 金昌市| 定日县| 石渠县| 通城县| 南丰县| 秦皇岛市| 搜索| 洛扎县| 辉县市| 鄂伦春自治旗| 张掖市| 邵阳市| 阿合奇县| 理塘县| 兴义市| 涞水县| 新巴尔虎右旗| 遂宁市| 沙雅县| 阜阳市| 施甸县| 新晃| 禄劝| 东丽区| 临泉县| 浙江省| 苏州市|