Make it easier to exit a background task when the socket disconnects
Describe the Features For some use cases, I want to have an infinite loop that runs while the page is active and connected. Currently this can be accomplished via
@rx.event(background=True)
async def my_infinite_task(self):
from app.app import app
task_sid = self.router.session.session_id
while task_sid == (
app._event_namespace.token_to_sid.get(self.router.session.client_token, None)
):
# do stuff
await asyncio.sleep(5)
# do cleanup
- What is the purpose of the feature?
I want to write that same thing as
@rx.event(background=True, cancel=rx.Cancel.ON_DISCONNECT)
async def my_infinite_task(self):
try:
while True:
# do stuff
await asyncio.sleep(5)
except asyncio.CancelledError:
# do cleanup
Additional context Although there are more event driven ways to accomplish this (like rx.moment), this method is probably the most familiar approach (and common in llm generated code)
In case it matters, this would be useful also in non-background tasks. In my use case, I'm using reflex for generating a constantly growing report that doesn't require the reflex event loop.
BTW, thanks a lot for posting this issue and the workaround, masenf. I ran into this and would spend a lot more time dealing with it if it wasn't for you.
Talking about background tasks, could this be a way to connect to mqtt broker from reflex and plot the data being collected in real time? I opened an issue [https://github.com/reflex-dev/reflex/issues/5061] over a week ago regarding this problem and my sample code but haven't gotten any response from anyone regarding a way to accomplish this.