From 37219ffbb64ffd057cb1fd69e1f880a2d93fab48 Mon Sep 17 00:00:00 2001 From: Brandon Rozek Date: Sat, 11 Jul 2020 20:46:33 -0400 Subject: [PATCH] New Post --- content/blog/asynccallbacks.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 content/blog/asynccallbacks.md diff --git a/content/blog/asynccallbacks.md b/content/blog/asynccallbacks.md new file mode 100644 index 0000000..d7de31b --- /dev/null +++ b/content/blog/asynccallbacks.md @@ -0,0 +1,23 @@ +--- +title: "Quick Python: Async Callbacks" +date: 2020-07-11T20:23:29-04:00 +draft: false +tags: ["python"] +--- + +I've written a post on using [callbacks in Python](https://brandonrozek.com/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: +```python +class Application: + # ... + def emit(self, message): + for callback in self.callbacks: + if asyncio.iscoroutine(callback): + loop = asyncio.get_running_loop() + loop.call_soon( + functools.partial( + asyncio.ensure_future, + callback(event, index) + ) + else: + callback(event, index) +```