Rxpy 简明教程
RxPY - Working With Observables
一个可观察对象是一个创建观察员并将其附加到预期值源(例如点击、DOM 元素上的鼠标事件等)的函数。
An observable, is a function that creates an observer and attaches it to the source where values are expected, for example, clicks, mouse events from a dom element, etc.
下面提及的主题将在本章中详细研究。
The topics mentioned below will be studied in detail in this chapter.
-
Create Observables
-
Subscribe and Execute an Observable
Create observables
要创建一个可观察对象,我们将使用 {}s0 方法并向其传递一个包含以下项的函数。
To create an observable we will use create() method and pass the function to it that has the following items.
-
on_next() − This function gets called when the Observable emits an item.
-
on_completed() − This function gets called when the Observable is complete.
-
on_error() − This function gets called when an error occurs on the Observable.
要使用 create() 方法,首先按下方所示导入该方法−
To work with create() method first import the method as shown below −
from rx import create
以下是创建一个 observable 的工作示例−
Here is a working example, to create an observable −
testrx.py
testrx.py
from rx import create
deftest_observable(observer, scheduler):
observer.on_next("Hello")
observer.on_error("Error")
observer.on_completed()
source = create(test_observable).
Subscribe and Execute an Observable
要订阅一个 observable,我们需要使用 subscribe() 函数,并传递回调函数 on_next、on_error 和 on_completed。
To subscribe to an observable, we need to use subscribe() function and pass the callback function on_next, on_error and on_completed.
以下是工作示例−
Here is a working example −
testrx.py
testrx.py
from rx import create
deftest_observable(observer, scheduler):
observer.on_next("Hello")
observer.on_completed()
source = create(test_observable)
source.subscribe(
on_next = lambda i: print("Got - {0}".format(i)),
on_error = lambda e: print("Error : {0}".format(e)),
on_completed = lambda: print("Job Done!"),
)
subscribe() 方法负责执行 observable。回调函数 on_next 、 on_error 和 on_completed 必须传递给 subscribe 方法。随后对 subscribe 方法的调用将执行 test_observable() 函数。
The subscribe() method takes care of executing the observable. The callback function on_next, on_error and on_completed has to be passed to the subscribe method. Call to subscribe method, in turn, executes the test_observable() function.
不必将所有三个回调函数都传递给 subscribe() 方法。您可以根据自己的需要传递 on_next()、on_error() 和 on_completed()。
It is not mandatory to pass all three callback functions to the subscribe() method. You can pass as per your requirements the on_next(), on_error() and on_completed().
lambda 函数用于 on_next、on_error 和 on_completed。它将采用参数并执行给定的表达式。
The lambda function is used for on_next, on_error and on_completed. It will take in the arguments and execute the expression given.
以下是创建的 observable 的输出−
Here is the output, of the observable created −
E:\pyrx>python testrx.py
Got - Hello
Job Done!