Reader.read()需要无限地收听 Api.listen(),而后者又无限地收听打开的网络套接字。 编写以下代码的正确方法是什么?
class Api:
async def listen(self):
async with websockets.connect(URL) as sock:
while True:
yield await sock.recv()
class Reader:
async def read(self):
api = Api()
while True:
data = await api.listen()
...
reader = Reader()
reader.read()
不足为奇,此代码会产生错误:
TypeError: object async_generator can't be used in 'await' expression
我应该实现类似Api.Listen.__await__()
的东西吗?
如何正确编码这样的异步读取良率模式?