gpt4 book ai didi

python - 通过 rxpy 从 observable 返回一个值

转载 作者:行者123 更新时间:2023-11-28 22:24:50 25 4
gpt4 key购买 nike

在函数中将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com