async def test_pipe_complex_pipe(): xs = AsyncObservable.from_iterable([1, 2, 3]) result = [] def mapper(value): return value * 10 async def predicate(value): await asyncio.sleep(0.1) return value > 1 async def long_running(value): return AsyncObservable.from_iterable([value]) ys = pipe(xs, op.filter(predicate), op.map(mapper), op.flat_map(long_running) ) async with subscribe(ys) as stream: async for value in stream: result.append(value) assert result == [20, 30]
async def test_forward_pipe_simple_pipe() -> None: xs = AsyncObservable.from_iterable([1, 2, 3]) result = [] def mapper(value) -> int: return value * 10 async def predicate(value) -> bool: await asyncio.sleep(0.1) return value > 1 ys = xs | op.filter(predicate) | op.map(mapper) async def asend(value) -> None: result.append(value) await run(ys, AnonymousAsyncObserver(asend)) assert result == [20, 30]
async def test_pipe_simple_pipe(): xs = AsyncObservable.from_iterable([1, 2, 3]) result = [] def mapper(value): return value * 10 async def predicate(value): await asyncio.sleep(0.1) return value > 1 ys = pipe(xs, op.filter(predicate), op.map(mapper) ) async def asend(value): result.append(value) await run(ys, AnonymousAsyncObserver(asend)) assert result == [20, 30]
async def websocket_handler(request): print("WebSocket opened") stream = AsyncStream() # Line break before binary operator is more readable. Disable W503 xs = ( stream | op.map(lambda x: x["term"]) | op.filter(lambda text: len(text) > 2) | op.debounce(0.75) | op.distinct_until_changed() | op.flat_map(search_wikipedia) #| op.switch_latest() ) ws = web.WebSocketResponse() await ws.prepare(request) async def asend(value): ws.send_str(value) async def athrow(ex): print(ex) await subscribe(xs, AnonymousAsyncObserver(asend, athrow)) async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: obj = json.loads(msg.data) await stream.asend(obj) elif msg.type == aiohttp.WSMsgType.ERROR: print('ws connection closed with exception %s' % ws.exception()) print('websocket connection closed') return ws