我有一个source
observable,我订阅了一个logger
观察者来进行日志记录。
我也订阅了,source
所以我可以执行计算。当我的计算完成后,我已经完成source
并且我想处理logger
:
+-------------------+
| |
+---------+ source observable +--------+
| | | |
| +-------------------+ |
| |
| |
+--v---------------+ +------------v--------+
| | | |
| logger | | computations |
| (observer) | | (observable) |
+-------^----------+ +-----------+---------+
| |
| |
| dispose logger |
+--------------------------------+
when computations completed
但是,logger
并没有在正确的时间完全处理——通常会发生一两个额外的滴答声:
MWE
from rx import Observable
# Some source
source = Observable.interval(1)
# Create logger for source
logged = []
logger = source.subscribe(logged.append)
# Now do stuff/computations with source
calculated = source.map(lambda x: x**2).take_while(lambda x: x < 20)
# Output computed values and stop logging when we're done with our computation
calculated.subscribe(print, print, logger.dispose)
# I expect only values that passed through our computation to have been logged
# The last value should be 5 because 5**2 = 25 which is larger than 20
# which in turn causes our computation to terminate
assert logged == [0, 1, 2, 3, 4, 5], logged
但我得到:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-54-e8cb1fb583bf>", line 1, in <module>
assert logged == [0, 1, 2, 3, 4, 5], logged
AssertionError: [0, 1, 2, 3, 4, 5, 6, 7]
7是如何被记录的?我们的计算应该在发出 5 次后终止source
,此时logger
会处理掉。
我究竟做错了什么?