将 rx.Observable 对象转换为函数中的“普通”对象的优雅方法是什么?
例如:
def foo():
return rx.Observable.just('value').subscribe(<some magic here>)
>>> print(foo())
# expected:
# value
# however get:
# <rx.disposables.anonymousdisposable.AnonymousDisposable at SOME ADDRESS>
我知道 subscribe 的返回是一个一次性对象,实现这一点的“丑陋”方式是:
class Foo:
def __init__(self):
self.buffer = None
def call_kernel(self):
rx.Observable.just('value').subscribe(lambda v: self.buffer = v)
def __call__(self):
self.call_kernel()
return self.buffer
>>> Foo()
# get:
# value
有没有更好的方法来做到这一点?
谢谢。
最佳答案
看一下 Observable::to_blocking()
:它创建一个 BlockingObservable
,它可强制转换为包含所有发出项目的列表。举个例子:
def foo():
return list(rx.Observable.just('value').to_blocking())[0]
我还想指出您的第二个解决方案是危险的,因为无法保证何时发出值,并且您的 __call__
依赖于 'value'
立即发出。
关于python - 通过 rxpy 从 observable 返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46051331/