Rxpy 简明教程
RxPY - Latest Release Updates
在本教程中,我们使用 RxPY 3 版和 Python 3.7.3 版。RxPY 3 版的工作方式与早期版本(即 RxPY 1 版)略有不同。
In this tutorial, we are using RxPY version 3 and python version 3.7.3. The working of RxPY version 3 differs a little bit with the earlier version, i.e. RxPY version 1.
在本章中,我们将讨论这两个版本之间的差异以及在更新 Python 和 RxPY 版本时需要进行的更改。
In this chapter, we are going to discuss the differences between the 2 versions and changes that need to be done in case you are updating Python and RxPY versions.
Observable in RxPY
在 RxPy 1 版中,Observable 是一个单独的类——
In RxPy version 1, Observable was a separate class −
from rx import Observable
要使用 Observable,您必须按如下方式使用它——
To use the Observable, you have to use it as follows −
Observable.of(1,2,3,4,5,6,7,8,9,10)
在 RxPy 3 版中,Observable 直接是 rx 包的一部分。
In RxPy version 3, Observable is directly a part of the rx package.
Example
import rx
rx.of(1,2,3,4,5,6,7,8,9,10)
Operators in RxPy
在 1 版中,运算符是 Observable 类的成员函数。例如,要使用运算符,我们必须导入 Observable,如下所示——
In version 1, the operator was methods in the Observable class. For example, to make use of operators we have to import Observable as shown below −
from rx import Observable
运算符用作 Observable.operator,例如如下所示——
The operators are used as Observable.operator, for example, as shown below −
Observable.of(1,2,3,4,5,6,7,8,9,10)\
.filter(lambda i: i %2 == 0) \
.sum() \
.subscribe(lambda x: print("Value is {0}".format(x)))
对于 RxPY 3 版,运算符是函数,按如下方式导入和使用——
In the case of RxPY version 3, operators are function and are imported and used as follows −
import rx
from rx import operators as ops
rx.of(1,2,3,4,5,6,7,8,9,10).pipe(
ops.filter(lambda i: i %2 == 0),
ops.sum()
).subscribe(lambda x: print("Value is {0}".format(x)))
Chaining Operators Using Pipe() method
在 RxPy 1 版中,如果您必须对一个可观察对象使用多个运算符,则必须按如下方式进行——
In RxPy version 1, in case you had to use multiple operators on an observable, it had to be done as follows −
Example
from rx import Observable
Observable.of(1,2,3,4,5,6,7,8,9,10)\
.filter(lambda i: i %2 == 0) \
.sum() \
.subscribe(lambda x: print("Value is {0}".format(x)))
但是,在 RxPY 3 版中,您可以使用 pipe() 方法和多个运算符,如下所示——
But, in case of RxPY version 3, you can use pipe() method and multiple operators as shown below −
Example
import rx
from rx import operators as ops
rx.of(1,2,3,4,5,6,7,8,9,10).pipe(
ops.filter(lambda i: i %2 == 0),
ops.sum()
).subscribe(lambda x: print("Value is {0}".format(x)))