Issues with asyncio and Streamlit: Event bound to a different event loop

Looks like I figured it out. Somewhat of a hack, but it works more reliably now.

Need to run the async functions with this:

It’ll catch the weird event loop error and then rerun it, and avoids the problem.

import asyncio

def run_async_task(async_func, *args):
    """
    Run an asynchronous function in a new event loop.

    Args:
    async_func (coroutine): The asynchronous function to execute.
    *args: Arguments to pass to the asynchronous function.

    Returns:
    None
    """
    
    loop = None

    try:
        loop = asyncio.new_event_loop()
        loop.run_until_complete(async_func(*args))
    except:
        # Close the existing loop if open
        if loop is not None:
            loop.close()

        # Create a new loop for retry
        loop = asyncio.new_event_loop()

        loop.run_until_complete(async_func(*args))
    finally:
        if loop is not None:
            loop.close()
1 Like