website/content/blog/asynccallbacks.md

26 lines
840 B
Markdown
Raw Permalink Normal View History

2020-07-11 20:46:33 -04:00
---
title: "Quick Python: Async Callbacks"
date: 2020-07-11T20:23:29-04:00
draft: false
2022-01-02 14:24:29 -05:00
tags: ["Python"]
2023-01-05 14:04:45 -05:00
medium_enabled: true
2020-07-11 20:46:33 -04:00
---
I've written a post on using [callbacks in Python](/blog/pysubscribepattern/). Though to add callbacks to `asyncio` functions, you'll have to interact with the loop object directly. Replace the emit function in the previous post with the following:
2020-07-11 20:46:33 -04:00
```python
class Application:
# ...
def emit(self, message):
for callback in self.callbacks:
2020-07-11 20:47:46 -04:00
if asyncio.iscoroutine(callback):
loop = asyncio.get_running_loop()
loop.call_soon(
functools.partial(
2020-07-11 20:46:33 -04:00
asyncio.ensure_future,
2020-07-11 20:48:52 -04:00
callback(message)
2020-07-11 20:47:46 -04:00
)
)
else:
2020-07-11 20:48:52 -04:00
callback(message)
2020-07-11 20:46:33 -04:00
```