我希望能够在恰好是BehaviorSubject的流上使用重播运算符。 本质上,我希望印刷版订阅接收预先发送的排放:0、1、2、3、4、5。
我试图用.subscribe()
使可观察的热点。另外,我确实知道将来源设为ReplaySubject
可以解决问题,但这对我来说不是一个选择。
与大多数语言不同,Python的rx v3.0
使用管道命令来链接操作(例如replay()
或ref_count()
或publish()
),而不是通常的'。链。这是管道命令的链接:https://rxpy.readthedocs.io/en/latest/migration.html#pipe-based-operator-chaining
我非常确定问题与我给replay()的第一个参数有关:lambda x: x
。
import rx.subject
from rx import operators as op
stream = rx.subject.BehaviorSubject(0)
replayable_observable = stream.pipe(op.replay(lambda x: x, buffer_size=100))
replayable_observable.subscribe()
stream.subscribe()
for x in [1, 2, 3, 4, 5]:
stream.on_next(x)
replayable_observable.subscribe(lambda value: print("Received {0}".format(value)))
for x in [6, 7, 8, 9, 10]:
stream.on_next(x)
我希望收到0-10
;或1-10
。但是相反,我收到了5-10
。
Received 5
Received 6
Received 7
Received 8
Received 9
Received 10
答案 0 :(得分:0)
似乎replay
的第一个参数(mapper
函数)旨在允许您在多播后将更多运算符链接到可观察的源上。例如,如果将其从lambda x: x
更改为lambda x: x.pipe(op.map(lambda y: y * 2))
,您将获得加倍的值。
replay
的{{3}}似乎已过时,因为他们给出的示例mapper
函数仍然使用旧方法链而不是管道方法。此外,在replay
参数中实际上使用非默认值的所有mapper
的{{3}}在该项目的GitHub存储库中似乎已被注释掉,因此没有明确的示例如何正确使用此参数。
通过查看源代码,我可以说的是,当您使用replay
而不指定mapper
时,您将得到一个ConnectableObservable
而不是Observable
。在将值正确推入主题之前连接此ConnectableObservable
可以缓冲结果。
import rx.subject
from rx import operators as op
stream = rx.subject.BehaviorSubject(0)
replayable_observable = stream.pipe(op.replay(buffer_size=100))
replayable_observable.connect()
for x in [1, 2, 3, 4, 5]:
stream.on_next(x)
replayable_observable.subscribe(lambda value: print("Received {0}".format(value)))
for x in [6, 7, 8, 9, 10]:
stream.on_next(x)
# Received 0
# Received 1
# Received 2
# Received 3
# Received 4
# Received 5
# Received 6
# Received 7
# Received 8
# Received 9
# Received 10